using System.Security.Cryptography;
public static string EncryptStringToBytes_Aes(string password, byte[] Key, byte[] IV)
if (password == null || password.Length <= 0)
throw new ArgumentNullException("password");
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())
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
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(password);
encrypted = Convert.ToBase64String(msEncrypt.ToArray());
public static string DecryptStringFromBytes_Aes(string 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())
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
plaintext = srDecrypt.ReadToEnd();
public static void Main()
var key = Encoding.UTF8.GetBytes("2D51C61B629D914D9C6AB38E8C9863118664A3DD52D6FC81E57841A33080671F").Take(32).ToArray();
var IV = Encoding.UTF8.GetBytes("!QAZ2WYX#EDC4RFV").Take(16).ToArray();
string plaintext = "Test PS";
var ciphertext = EncryptStringToBytes_Aes(plaintext, key, IV);
Console.WriteLine(ciphertext);
var de = DecryptStringFromBytes_Aes(ciphertext, key, IV);