using System.Security.Cryptography;
public static void Main()
string original = "Here is some data to encrypt!";
using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
Console.WriteLine("Original: {0} \n", original);
byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV);
Console.WriteLine("Encrypted: {0} \n", System.Text.Encoding.UTF8.GetString(encrypted));
string decrypted = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);
Console.WriteLine("Decrypted Trip: {0}", decrypted);
Console.WriteLine("Error: {0}", e.Message);
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 (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
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 (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
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();