Skip to content

Instantly share code, notes, and snippets.

@manhnguyenv
Forked from yetanotherchris/aes-example.cs
Created January 7, 2019 04:49
Show Gist options
  • Select an option

  • Save manhnguyenv/e37664f7cd4717ab2384523124926f9c to your computer and use it in GitHub Desktop.

Select an option

Save manhnguyenv/e37664f7cd4717ab2384523124926f9c to your computer and use it in GitHub Desktop.
C# AES asymmetric encryption and decryption example
string ivAsBase64;
string encryptedTextAsBase64;
string keyAsBase64;
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
{
// Store the IV (they can be stored if you don't re-use a key)
aes.GenerateIV();
byte[] iv = aes.IV;
ivAsBase64 = Convert.ToBase64String(iv);
Console.WriteLine("IV base64: {0}", ivAsBase64);
// See how long the default key length is
aes.GenerateKey();
Console.WriteLine("Algorithm key length should be: {0}", aes.Key.Length);
// Set a key
string key = "a very long sentence for a key that should exceed the max length of a key for AES therefore we're going to need to substring it based on the GenerateKey length we're given";
Console.WriteLine("Key length: {0}", key.Length);
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, aes.Key.Length));
aes.Key = keyBytes;
Console.WriteLine("Key length is now: {0}", aes.Key.Length);
// Base64 the key for storage
keyAsBase64 = Convert.ToBase64String(aes.Key);
Console.WriteLine("Key base64: {0}", keyAsBase64);
// Encrypt the text
byte[] textBytes = Encoding.UTF8.GetBytes("chris áááéééééé óóóó 💩");
var cryptor = aes.CreateEncryptor();
byte[] encryptedBytes = cryptor.TransformFinalBlock(textBytes, 0, textBytes.Length);
encryptedTextAsBase64 = Convert.ToBase64String(encryptedBytes);
Console.WriteLine("Encrypted (base64'd): {0}", encryptedTextAsBase64);
}
Console.WriteLine("==================================================");
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
{
// Decrypt the text
byte[] iv = Convert.FromBase64String(ivAsBase64);
byte[] keyBytes = Convert.FromBase64String(keyAsBase64);
byte[] fromBase64ToBytes = Convert.FromBase64String(encryptedTextAsBase64);
var decryptor = aes.CreateDecryptor(keyBytes, iv);
byte[] decryptedBytes = decryptor.TransformFinalBlock(fromBase64ToBytes, 0, fromBase64ToBytes.Length);
Console.WriteLine("Decrypted: {0}", Encoding.UTF8.GetString(decryptedBytes));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment