using System.Security.Cryptography;
public static void Main()
string original = "Texto encriptado";
using (Aes myAes = Aes.Create())
byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV);
Console.WriteLine("Key Length: {0}", myAes.Key.Length);
Console.WriteLine("IV Length: {0}", myAes.IV.Length);
Console.WriteLine("Key: {0}", Convert.ToBase64String(myAes.Key, 0, myAes.Key.Length, Base64FormattingOptions.None));
Console.WriteLine("IV: {0}", Convert.ToBase64String(myAes.IV, 0, myAes.IV.Length, Base64FormattingOptions.None));
Console.WriteLine("Encrypted: {0}", Convert.ToBase64String(encrypted, 0, encrypted.Length, Base64FormattingOptions.None));
Console.WriteLine("Original: {0}", original);
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();