AES Encryption in C#: Code Example
In C#, AES encryption can be implemented using the AesManaged class. Below is a simple example code:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class AesEncryption
{
public static string Encrypt(string plainText, string key, string iv)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
byte[] encryptedBytes;
using (AesManaged aes = new AesManaged())
{
aes.Key = keyBytes;
aes.IV = ivBytes;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
encryptedBytes = ms.ToArray();
}
}
}
return Convert.ToBase64String(encryptedBytes);
}
public static string Decrypt(string encryptedText, string key, string iv)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
string decryptedText;
using (AesManaged aes = new AesManaged())
{
aes.Key = keyBytes;
aes.IV = ivBytes;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream(encryptedBytes))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
decryptedText = sr.ReadToEnd();
}
}
}
}
return decryptedText;
}
}
By using the code above, you can encrypt by calling the AesEncryption.Encrypt method and decrypt by calling the AesEncryption.Decrypt method. Please note that you need to provide a key and an initialization vector, both of which must be the same in order to decrypt correctly.