【发布时间】:2016-08-15 13:01:25
【问题描述】:
我正在使用微软的RSACryptoServiceProvider 类来加密/解密数据。
但是,解密函数会抛出异常“Bad Data”。
每次我使用加密/解密时都会创建提供程序类的新实例吗?
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 类创建一个实例有关,而不是每次使用它时都创建一个新实例。
【问题讨论】:
-
是的,我什至想查看谷歌的第二页。
-
有趣,这个问题是由创建第二个 RSACryptoServiceProvider 时创建的新密钥集引起的。然而,在 MSDN (msdn.microsoft.com/en-us/library/zseyf239(v=vs.110).aspx) 中提到了“默认密钥”,但没有关于其实际含义的文档。
标签: c# encryption cryptography rsa