Using AES encryption in C#

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.

I can't seem to find a nice clean example of using AES 128 bit encryption. Does anyone have some sample code?

28.3k 29 29 gold badges 101 101 silver badges 127 127 bronze badges asked Nov 7, 2008 at 20:03 Pretty good article on this here: codeproject.com/Articles/769741/… Commented Jul 17, 2014 at 7:05 Comments disabled on deleted / locked posts / reviews |

10 Answers 10

If you just want to use the built-in crypto provider RijndaelManaged, check out the following help article (it also has a simple code sample):

And just in case you need the sample in a hurry, here it is in all its plagiarized glory:

using System; using System.IO; using System.Security.Cryptography; namespace RijndaelManaged_Example < class RijndaelExample < public static void Main() < try < string original = "Here is some data to encrypt!"; // Create a new instance of the RijndaelManaged // class. This generates a new key and initialization // vector (IV). using (RijndaelManaged myRijndael = new RijndaelManaged()) < myRijndael.GenerateKey(); myRijndael.GenerateIV(); // Encrypt the string to an array of bytes. byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV); // Decrypt the bytes to a string. string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV); //Display the original data and the decrypted data. Console.WriteLine("Original: ", original); Console.WriteLine("Round Trip: ", roundtrip); > > catch (Exception e) < Console.WriteLine("Error: ", e.Message); > > static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV) < // Check arguments. if (plainText == null || plainText.Length encrypted = msEncrypt.ToArray(); > > > // Return the encrypted bytes from the memory stream. return encrypted; > static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV) < // Check arguments. if (cipherText == null || cipherText.Length > > > return plaintext; > > > 
5,153 2 2 gold badges 34 34 silver badges 54 54 bronze badges answered Nov 7, 2008 at 20:15 Dan Esparza Dan Esparza 28.3k 29 29 gold badges 101 101 silver badges 127 127 bronze badges

Your code doesn't store the IV along with the ciphertext, making it hard to use correctly, and easy to abuse. An IV isn't a secondary key, it should be randomly generated for each encryption, and stored alongside the ciphertext.

Commented Feb 18, 2012 at 17:03 For future readers: I have updated the code sample here with updated code from the sample on MSDN Commented May 14, 2013 at 13:09 Also: Don't forget that you're most likely dangerously bad at cryptography. happybearsoftware.com/… Commented May 28, 2013 at 18:11

Sure, there you go. msdn.microsoft.com/de-de/library/… Take a look at remarks. You can use rijndael but it could lead to compatibility issues, when you channge settings. Therefor I would use Aes-Class if you want to encrypt with AES(FIPS-197)

Commented Sep 20, 2013 at 5:11

@EricJ. The using () block automatically disposes the myRijndael object (and every other RijndaelManaged object in this example). Perhaps your comment was for an earlier version of the answer, or the link were showing bad examples, but that's not the case today.

Commented Jul 20, 2017 at 7:07

I've recently had to bump up against this again in my own project - and wanted to share the somewhat simpler code that I've been using, as this question and series of answers kept coming up in my searches.

I'm not going to get into the security concerns around how often to update things like your Salt and Initialization Vector - that's a topic for a security forum, and there are some great resources out there to look at. This is simply a block of code to implement AesManaged in C#.

using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace Your.Namespace.Security < public static class Cryptography < #region Settings private static int _iterations = 2; private static int _keySize = 256; private static string _hash = "SHA1"; private static string _salt = "aselrias38490a32"; // Random private static string _vector = "8947az34awl34kjq"; // Random #endregion public static string Encrypt(string value, string password) < return Encrypt(value, password); > public static string Encrypt(string value, string password) where T : SymmetricAlgorithm, new() < byte[] vectorBytes = GetBytes(_vector); byte[] saltBytes = GetBytes(_salt); byte[] valueBytes = GetBytes(value); byte[] encrypted; using (T cipher = new T()) < PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(password, saltBytes, _hash, _iterations); byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8); cipher.Mode = CipherMode.CBC; using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes)) < using (MemoryStream to = new MemoryStream()) < using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) < writer.Write(valueBytes, 0, valueBytes.Length); writer.FlushFinalBlock(); encrypted = to.ToArray(); >> > cipher.Clear(); > return Convert.ToBase64String(encrypted); > public static string Decrypt(string value, string password) < return Decrypt(value, password); > public static string Decrypt(string value, string password) where T : SymmetricAlgorithm, new() < byte[] vectorBytes = GetBytes(_vector); byte[] saltBytes = GetBytes(_salt); byte[] valueBytes = Convert.FromBase64String(value); byte[] decrypted; int decryptedByteCount = 0; using (T cipher = new T()) < PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(password, saltBytes, _hash, _iterations); byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8); cipher.Mode = CipherMode.CBC; try < using (ICryptoTransform decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes)) < using (MemoryStream from = new MemoryStream(valueBytes)) < using (CryptoStream reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read)) < decrypted = new byte[valueBytes.Length]; decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length); >> > > catch (Exception ex) < return String.Empty; >cipher.Clear(); > return Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount); > > > 

The code is very simple to use. It literally just requires the following:

string encrypted = Cryptography.Encrypt(data, "testpass"); string decrypted = Cryptography.Decrypt(encrypted, "testpass"); 

By default, the implementation uses AesManaged - but you could actually also insert any other SymmetricAlgorithm . A list of the available SymmetricAlgorithm inheritors for .NET 4.5 can be found at:

As of the time of this post, the current list includes:

To use RijndaelManaged with the code above, as an example, you would use:

string encrypted = Cryptography.Encrypt(dataToEncrypt, password); string decrypted = Cryptography.Decrypt(encrypted, password); 

I hope this is helpful to someone out there.