http://msdn.microsoft.com/en-us/library/vstudio/system.security.cryptography.rsacryptoserviceprovider.encrypt(v=vs.90).aspxに示されているように、保存されているRSAキーを使用しようとしています。ユーザーコンテナで、app.configファイル(NTサービス内)に保存されているRijndaelManagedKeyと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));
設定ファイルからキーと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の結果のバイト配列が異なるため、サービスを再起動する前に暗号化されたデータの復号化が試行され、PaddingInvalidエラーが発生して失敗します。
質問:構成ファイルの同じ暗号化データで同じRSAキーを使用している場合、サービスを再起動すると、結果のキーとIVの値が異なるのはなぜですか?
注:これは、OnStart()サービスメソッドで値を復号化してから、プロジェクトに追加されたdllで同じ値を復号化しようとした場合にも発生します。