Steve O. Ams, Jr. Ego Magnus Numen
Ego Magnus Numen

AES Decryption

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)
	byte[] iv = aes.IV;
	ivAsBase64 = Convert.ToBase64String(iv);
	Console.WriteLine("IV base64: {0}", ivAsBase64);

	// See how long the default key length is
	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("steve 123456");
	var cryptor = aes.CreateEncryptor();
	byte[] encryptedBytes = cryptor.TransformFinalBlock(textBytes, 0, textBytes.Length);
	encryptedTextAsBase64 = Convert.ToBase64String(encryptedBytes);
	Console.WriteLine("Encrypted (base64'd): {0}", encryptedTextAsBase64);


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));