As illustrated in http://msdn.microsoft.com/en-us/library/vstudio/system.security.cryptography.rsacryptoserviceprovider.encrypt(v=vs.90).aspx I am trying to use an RSA key that is stored in a User Container to encrypt and decrypt a RijndaelManaged Key and IV that is stored in an app.config file (in an NT service).
To create the encrypted keys I did the following and then added the strings to the config file
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));
When I go to use the Key and IV from the config file, I perform the following:
//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;
....
}
While the service is running RM.Key and RM.IV stay the same. If the service is restarted, the resulting byte arrays in RM.IV and RM.Key are different which causes any decryption attempt on data that was encrypted before the service was restarted to fail with a Padding Invalid error.
Question: If I am using the same RSA key on the same encrypted data from the config file, why are the resulting Key and IV values different when the service is restarted?
Note: This also happens if I decrypt the values in my OnStart() service method and then try to decrpyt the same values in a dll that has been added to the project.