我正在尝试实现内存中的 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))