I'm using microsoft's RSACryptoServiceProvider class to Encrypt/Decrypt data.
However, decryption function throws an exception "Bad Data".
Is it something about creating new instance of the provider class everytime I use encryption/decryption?
RSA Provider Class
static public byte[] RSAEncrypt(byte[] byteEncrypt, RSAParameters RSAInfo, bool isOAEP)
{
try
{
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSA.ImportParameters(RSAInfo);
//Encrypt the passed byte array and specify OAEP padding.
return RSA.Encrypt(byteEncrypt, isOAEP);
}
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
}
static public byte[] RSADecrypt(byte[] byteDecrypt, RSAParameters RSAInfo, bool isOAEP)
{
try
{
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(4096))
{
//Import the RSA Key information. This needs
//to include the private key information.
RSA.ImportParameters(RSAInfo);
//Decrypt the passed byte array and specify OAEP padding.
return RSA.Decrypt(byteDecrypt, isOAEP);
}
}
catch (CryptographicException e)
{
Console.WriteLine(e.ToString());
return null;
}
}
}
Usage
UnicodeEncoding ByteConverter = new UnicodeEncoding();
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(4096);
byte[] plainPassword;
byte[] encryptedPassword;
plainPassword = ByteConverter.GetBytes(connectionStringPasswordTextBox.Text);
encryptedPassword = CryptoHelper.RSAEncrypt(plainPassword, RSA.ExportParameters(false), false);
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(4096);
byte[] decryptedPassword = CryptoHelper.RSADecrypt(Convert.FromBase64String(connectionString.password), RSA.ExportParameters(true), false);
EDIT
The exception has changed to "The parameter is incorrect" after giving a few more try. I think it has to do with creating only one instance for rsa class instaead of creating new one everytime I use it.