インメモリ AESManaged 暗号化/復号化を実装しようとしています。ここでのコードはこれに基づいています。
暗号化部分は機能しているようです。つまり、例外はありません。しかし、復号化部分は「インデックスが配列の境界外でした」というエラーをスローします。
以前のコードでは、変換は次のように初期化されます。
aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(Key, salt, 1);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
transform = aes.CreateDecryptor(aes.Key, aes.IV);
void AESDecrypt(ref byte[] inB)
{
using (MemoryStream destination = new MemoryStream(inB, 0, inB.Length))
{
using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
{
try
{
using (MemoryStream source = new MemoryStream(inB, 0, inB.Length))
{
if (source.CanWrite==true)
{
source.Write(inB, 0, inB.Length);
source.Flush(); //<<inB is unchanged by the write
}
}
}
catch (CryptographicException exception)
{
if (exception.Message == "Padding is invalid and cannot be removed.")
throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception);
else
throw;
}
}
} <====At this point I get an IndexOutofBounds exception.
}
}
問題のある行は次のようです: using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))