I am trying to implement an in-memory AESManaged encrypt/decrypt. The code here is based on this:
Encrypting/Decrypting large files (.NET)
The encrypt part seems to work, that is, there are no exceptions. But the decrypt part throws an "index was outside the bounds of the array" error.
In earlier code the transform is initialize like this:
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.
}
}
It seems that the offending line may be: using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))