Using AES in C# I wrote two static methods for encryption and decryption.
Encrypt:
static byte[] Encrypt(byte[] plaintext, byte[] Key, byte[] IV)
{
byte[] encrypted_data = null;
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plaintext);
}
}
encrypted_data = msEncrypt.ToArray();
}
}
return encrypted_data;
}
Decrypt:
static string Decrypt(byte[] encrypted_text, byte[] Key, byte[] IV)
{
string decrypted_data = null;
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(encrypted_text))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
decrypted_data = srDecrypt.ReadToEnd();
return decrypted_data;
}
}
}
}
}
static void Main(string[] args)
{
byte[] Key = GenerateRandomKey(32);
byte[] IV = GenerateRandomIV(16);
byte[] data_to_encrypt = Encoding.UTF8.GetBytes("Hola como estas");
byte[] encrypted_data = Encrypt(data_to_encrypt, Key, IV);
File.WriteAllBytes("encrypted.enc", encrypted_data);
byte[] data_to_decrypt = File.ReadAllBytes("encrypted.enc");
string decrypted_data = Decrypt(data_to_decrypt, Key, IV);
Console.WriteLine(decrypted_data);
}
I use them in Main() where I generate a random 256-bit key and an IV of 128. I get the bytes of the string I want to encrypt and use the function to encrypt them, then write them to a file and read them again to decrypt but when trying to display them in the console it only shows the type "System.Byte[]".
Why does this happen instead of showing the decrypted data string?
StreamWriterclass?StreamWriter(as in the MS example) or omitting theStreamWriterwhen using the encoded data, are also possible solutions that should be addressed.