我正在使用微软的RSACryptoServiceProvider
类来加密/解密数据。 但是,解密函数会抛出一个异常“错误的数据”。 每次使用加密/解密时,是否需要创建提供程序类的新实例?c#Rsa解密引发“坏数据”异常
RSA提供者类
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;
}
}
}
使用
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);
编辑
例外已更改为 “参数不正确” 给多了一些尝试后。我认为这与创建一个rsa类instaead的实例有关,每次创建新实例时都会使用它。
你检查出这个:http://stackoverflow.com/questions/9659898/bad -data-cryptographicexception? –
是的,我甚至不顾一切地查看谷歌的第二页。 – Miral
有趣的是,当创建第二个RSACryptoServiceProvider时,由创建一个新的密钥集导致该问题。然而,MSDN提供了一个“默认键”(https://msdn.microsoft.com/en-us/library/zseyf239(v=vs.110).aspx),但没有关于实际含义的文档。 –