Encryption RSA Decrypt为相同的数据返回不同的byte[]结果

Encryption RSA Decrypt为相同的数据返回不同的byte[]结果,encryption,bytearray,rsa,rijndaelmanaged,Encryption,Bytearray,Rsa,Rijndaelmanaged,如中所示,我尝试使用存储在用户容器中的RSA密钥加密和解密RijndaelManaged密钥以及存储在app.config文件(在NT服务中)中的IV 为了创建加密密钥,我执行了以下操作,然后将字符串添加到配置文件中 当我使用配置文件中的密钥和IV时,我执行以下操作: 当服务运行时,RM.Key和RM.IV保持不变。如果重新启动服务,则RM.IV和RM.Key中产生的字节数组不同,这会导致对服务重新启动前加密的数据进行的任何解密尝试失败,并出现填充无效错误 问题:如果我对配置文件中相同的

如中所示,我尝试使用存储在用户容器中的RSA密钥加密和解密RijndaelManaged密钥以及存储在app.config文件(在NT服务中)中的IV

为了创建加密密钥,我执行了以下操作,然后将字符串添加到配置文件中



当我使用配置文件中的密钥和IV时,我执行以下操作:



当服务运行时,RM.Key和RM.IV保持不变。如果重新启动服务,则RM.IV和RM.Key中产生的字节数组不同,这会导致对服务重新启动前加密的数据进行的任何解密尝试失败,并出现填充无效错误

问题:如果我对配置文件中相同的加密数据使用相同的RSA密钥,为什么重新启动服务时生成的密钥和IV值不同?


注意:如果我解密OnStart()服务方法中的值,然后尝试在已添加到项目的dll中还原相同的值,也会发生这种情况。

胡乱猜测:您的服务是否以您在容器中存储密钥的用户身份运行?您可以在此过程中添加一些跟踪(或调试),并查看是否每次都获得相同的RSA密钥。

感谢您的回复。是的,我检查了服务是否在创建密钥容器的同一用户下运行。我检查了RSA模和指数是否设置正确,它们似乎是正确的。加密密钥和IV呢?您是否总是从配置文件中获取相同的值?
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));
//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;
    ....

}