public static byte[] TestEncrypt(string plainText, byte[] key, byte[] iv)
{
using Aes aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
// Create a new MemoryStream object to contain the encrypted bytes.
using MemoryStream memoryStream = new MemoryStream();
// Create a CryptoStream object to perform the encryption.
using CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
// Encrypt the plaintext.
using StreamWriter streamWriter = new StreamWriter(cryptoStream);
streamWriter.Write(plainText);
cryptoStream.FlushFinalBlock();
byte[] cipherText = memoryStream.ToArray();
return cipherText;
}
public static string TestDecrypt(byte[] encryptedText, byte[] key, byte[] iv)
{
using Aes aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
using MemoryStream memoryStream = new MemoryStream(encryptedText);
memoryStream.Position = 0;
using CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
using StreamReader streamReader = new StreamReader(cryptoStream);
cryptoStream.Flush();
var data = streamReader.ReadToEnd() ;
return data;
}
I am using above two methods to encrypt and decrypt a string. I find that the streamreader always returns an empty string. I have verified multiple times that both the methods receive the same key and iv values including that the encrypted text is not modified/tampered when passed to TestDecrypt method.
I am still unable to figure out why an empty string is being returned ?
Please test the methods with any random key and IV value. I just want to know if the encrypted text is decrypted successfully.
I expect to see the encrypted text being successfully decrypted back to the original text. The result is an empty string which is incorrect.
cryptoStream.Flush()from theTestDecryptmethod? It looks suspicious for a read-only stream.