Ecrypt/decrypt with CryptoStream
Solution 1:
Thanks to Mathias R. Jassen for the suggestion. Following the working code:
public void Encrypt(Stream input, Stream output)
{
Aes aes = Aes.Create();
aes.Key = Key;
aes.IV = IV;
aes.Padding = PaddingMode.PKCS7;
//aes.Mode = CipherMode.CBC;
//aes.BlockSize = 128;
ICryptoTransform aesEncryptor = aes.CreateEncryptor();
using (CryptoStream cryptoStream = new(output, aesEncryptor, CryptoStreamMode.Write))
{
input.CopyTo(cryptoStream);
cryptoStream.FlushFinalBlock();
}
}
and
public void Decrypt(Stream input, Stream output)
{
Aes aes = Aes.Create();
aes.Key = Key;
aes.IV = IV;
aes.Padding = PaddingMode.PKCS7;
//aes.Mode = CipherMode.CBC;
//aes.BlockSize = 128;
ICryptoTransform aesDecryptor = aes.CreateDecryptor();
using (CryptoStream cryptoStream = new(input, aesDecryptor, CryptoStreamMode.Read))
{
cryptoStream.CopyTo(output);
cryptoStream.Close();
}
output.Flush();
}
Please, note the
output.Flush()
command!