using System.Security.Cryptography;
public static void Main()
string original = "Here is some data to encrypt!";
using (Aes myAes = Aes.Create())
byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV);
string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);
Console.WriteLine("Original: {0}", original);
foreach (byte i in encrypted)
System.Console.Write("{0} ", i);
copia.SetValue("{0} ",i);
foreach (byte i in copia)
System.Console.Write("{0} ", i);
copia.SetValue("{0} ",i);
Console.WriteLine(encrypted.GetValue(1));
Console.WriteLine("Round Trip: {0}", roundtrip);
static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
using (Aes aesAlg = Aes.Create())
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 = msEncrypt.ToArray();
static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
using (Aes aesAlg = Aes.Create())
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
plaintext = srDecrypt.ReadToEnd();