Skip to content

Instantly share code, notes, and snippets.

@BadgerCode
Created February 20, 2018 20:17
Show Gist options
  • Save BadgerCode/636d63e7975b109c56df247698126467 to your computer and use it in GitHub Desktop.
Save BadgerCode/636d63e7975b109c56df247698126467 to your computer and use it in GitHub Desktop.
C# AES encryption and decryption example
public static class AES
{
// Keys should be 32 bytes
public static string Encrypt(string text, byte[] key)
{
using (var memoryStream = new MemoryStream())
using (var aes = Aes.Create())
using (var encryptor = aes.CreateEncryptor(key, aes.IV))
{
memoryStream.Write(aes.IV, 0, aes.IV.Length);
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
using (var streamWriter = new StreamWriter(cryptoStream))
{
streamWriter.Write(text);
}
return Convert.ToBase64String(memoryStream.ToArray());
}
}
}
public static string Decrypt(string cipherText, byte[] key)
{
var cipherTextBytes = Convert.FromBase64String(cipherText);
using (var memoryStream = new MemoryStream(cipherTextBytes))
using (var aes = Aes.Create())
{
var initialState = new byte[aes.BlockSize / 8];
memoryStream.Read(initialState, 0, initialState.Length);
using (var decryptor = aes.CreateDecryptor(key, initialState))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
using (var streamReader = new StreamReader(cryptoStream))
{
return streamReader.ReadToEnd();
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment