我正在使用这样的 RSACryptoServiceProvider ...
private byte[] RSAEncrypt(byte[] DataToEncrypt, string ContainerName, bool DoOAEPPadding)
{
try
{
byte[] encryptedData;
// Create a new instance of CspParameters. Pass
// 13 to specify a DSA container or 1 to specify
// an RSA container. The default is 1.
CspParameters cspParams = new CspParameters();
// Specify the container name using the passed variable.
cspParams.KeyContainerName = ContainerName;
cspParams.Flags = CspProviderFlags.UseDefaultKeyContainer;
//Create a new instance of RSACryptoServiceProvider.
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(cspParams))
{
//Encrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
}
return encryptedData;
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException ex)
{
sl.Write(ex, MessageType.Error);
throw;
}
}
然后,我在关闭 Outlook Plugin Windows Form 应用程序并将其重新打开后尝试解密数据,这就是使用这段代码的原因。解密代码如下所示...
private byte[] RSAEncrypt(byte[] DataToEncrypt, string ContainerName, bool DoOAEPPadding)
{
try
{
byte[] encryptedData;
// Create a new instance of CspParameters. Pass
// 13 to specify a DSA container or 1 to specify
// an RSA container. The default is 1.
CspParameters cspParams = new CspParameters();
// Specify the container name using the passed variable.
cspParams.KeyContainerName = ContainerName;
cspParams.Flags = CspProviderFlags.UseDefaultKeyContainer;
//Create a new instance of RSACryptoServiceProvider.
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(cspParams))
{
//Encrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
}
return encryptedData;
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException ex)
{
sl.Write(ex, MessageType.Error);
throw;
}
}
效果很好,直到出现我无法解决的问题。不知道是不是日期变了还是什么。发生的情况是我尝试解密数据并且收到“错误数据”错误。现在它再次运行良好,直到经过一段时间,或者关闭应用程序,或者用户注销。我只是不知道也无法确定是什么原因造成的。当我吹走来自文本文件的加密数据并重新创建并解密它时,我没有问题。即使我在加密/保存到文件和从文件读取/解密之间重新启动应用程序,它也会很好用!发生了一些事情,我只是不太了解 KeyContainers 来理解什么可能使 CspParameters 过期是我最好的猜测?