如http://msdn.microsoft.com/en-us/library/vstudio/system.security.cryptography.rsacryptoserviceprovider.encrypt(v=vs.90).aspx中所示,我正在尝试使用存储的 RSA 密钥在用户容器中加密和解密存储在 app.config 文件中的 RijndaelManaged 密钥和 IV(在 NT 服务中)。
要创建加密密钥,我执行了以下操作,然后将字符串添加到配置文件
CspParameters cp = new CspParameters();
cp.KeyContainerName = "ContainerName";
// Get the existing or create a new RSA Key
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
//Create a new instance of the RijndaelManaged class.
RijndaelManaged RM = new RijndaelManaged();
//Encrypt the symmetric key and IV.
byte[] EncryptedSymmetricKey = rsa.Encrypt(RM.Key, false);
byte[] EncryptedSymmetricIV = rsa.Encrypt(RM.IV, false);
string configKey = Convert.ToBase64String(EncryptedSymmetricKey));
string configIV = Convert.ToBase64String(EncryptedSymmetricIV));
当我从配置文件中使用 Key 和 IV 时,我执行以下操作:
//Get the existing RSA Key from the USER Container identified by Provider in the appsettings
CspParameters cp = new CspParameters();
cp.KeyContainerName = "ContainerName";
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp))
{
//Decrypt the RijndaelManaged KEY and IV from the config file using the RSA Key
byte[] Encrypted_RM_Key = Convert.FromBase64String(AppSettings["configKey"]);
byte[] Encrypted_RM_IV = Convert.FromBase64String(AppSettings["configIV"]);
byte[] Decrypted_RM_Key = rsa.Decrypt(Encrypted_RM_Key, false);
byte[] Decrypted_RM_IV = rsa.Decrypt(Encrypted_RM_IV, false);
//Encrypt the file using RijndaelManaged
RijndaelManaged RM = new RijndaelManaged();
RM.Key = Decrypted_RM_Key;
RM.IV = Decrypted_RM_IV;
....
}
当服务运行时,RM.Key 和 RM.IV 保持不变。如果服务重新启动,RM.IV 和 RM.Key 中生成的字节数组不同,这会导致对在服务重新启动之前加密的数据进行的任何解密尝试失败,并出现 Padding Invalid 错误。
问题:如果我在配置文件中的相同加密数据上使用相同的 RSA 密钥,为什么重新启动服务时生成的密钥和 IV 值不同?
注意:如果我解密 OnStart() 服务方法中的值,然后尝试解密已添加到项目中的 dll 中的相同值,也会发生这种情况。