AES Encryption In C# (2024)

.NET provides high-level level classes for various encryption algorithms, both symmetric and asymmetric. Advanced Encryption Standard (AES) is one of the symmetric encryption algorithms that allows both parties, sender, and receiver, to use the same key to encrypt and decrypt data.

AES was developed by two Belgian cryptographers, Vincent Rijmen and Jan Daemen. In 2001, AES was selected as a standard for encryption by the U. S. National Institute of Standards and Technology (NIST). AES supports 128, 192, and 256 bits key sizes and 128 bits sizes.

AesManaged class is a managed implementation of the AES algorithm. This article demonstrates the use AesManaged class to apply an AES algorithm to encrypt and decrypt data in .NET and C#.

The following steps are required to encrypt data using AesManaged.

Step 1

Create AesManaged,

AesManagedaes=newAesManaged();

Step 2

Create Encryptor,

ICryptoTransformencryptor=aes.CreateEncryptor(Key,IV);

Step 3

Create MemoryStream,

MemoryStreamms=newMemoryStream();

Step 4

Create CryptoStream from MemoryStream and Encrypter and write it.

using(CryptoStreamcs=newCryptoStream(ms,encryptor,CryptoStreamMode.Write)){//CreateStreamWriterandwritedatatoastreamusing(StreamWritersw=newStreamWriter(cs))sw.Write(plainText);encrypted=ms.ToArray();}

The complete code is listed in Listing 1. To test the code, create a .NET Core project in Visual Studio and copy and paste the code.

usingSystem;usingSystem.IO;usingSystem.Security.Cryptography;classManagedAesSample{publicstaticvoidMain(){Console.WriteLine("Entertextthatneedstobeencrypted..");stringdata=Console.ReadLine();EncryptAesManaged(data);Console.ReadLine();}staticvoidEncryptAesManaged(stringraw){try{//CreateAesthatgeneratesanewkeyandinitializationvector(IV).//Samekeymustbeusedinencryptionanddecryptionusing(AesManagedaes=newAesManaged()){//Encryptstringbyte[]encrypted=Encrypt(raw,aes.Key,aes.IV);//PrintencryptedstringConsole.WriteLine($"Encrypteddata:{System.Text.Encoding.UTF8.GetString(encrypted)}");//decryptthebytestoastring.stringdecrypted=Decrypt(encrypted,aes.Key,aes.IV);//Printdecryptedstring.ItshouldbesameasrawdataConsole.WriteLine($"Decrypteddata:{decrypted}");}}catch(Exceptionexp){Console.WriteLine(exp.Message);}Console.ReadKey();}staticbyte[]Encrypt(stringplainText,byte[]Key,byte[]IV){byte[]encrypted;//CreateanewAesManaged.using(AesManagedaes=newAesManaged()){//CreateencryptorICryptoTransformencryptor=aes.CreateEncryptor(Key,IV);//CreateMemoryStreamusing(MemoryStreamms=newMemoryStream()){//CreatecryptostreamusingtheCryptoStreamclass.Thisclassisthekeytoencryption//andencryptsanddecryptsdatafromanygivenstream.Inthiscase,wewillpassamemorystream//toencryptusing(CryptoStreamcs=newCryptoStream(ms,encryptor,CryptoStreamMode.Write)){//CreateStreamWriterandwritedatatoastreamusing(StreamWritersw=newStreamWriter(cs))sw.Write(plainText);encrypted=ms.ToArray();}}}//Returnencrypteddatareturnencrypted;}staticstringDecrypt(byte[]cipherText,byte[]Key,byte[]IV){stringplaintext=null;//CreateAesManagedusing(AesManagedaes=newAesManaged()){//CreateadecryptorICryptoTransformdecryptor=aes.CreateDecryptor(Key,IV);//Createthestreamsusedfordecryption.using(MemoryStreamms=newMemoryStream(cipherText)){//Createcryptostreamusing(CryptoStreamcs=newCryptoStream(ms,decryptor,CryptoStreamMode.Read)){//Readcryptostreamusing(StreamReaderreader=newStreamReader(cs))plaintext=reader.ReadToEnd();}}}returnplaintext;}}

Listing 1.

The output looks like the following, where you can type any text that will be encrypted and decrypted.

AES Encryption In C# (1)

References

  • https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  • https://docs.microsoft.com
AES Encryption In C# (2024)
Top Articles
Latest Posts
Article information

Author: Corie Satterfield

Last Updated:

Views: 6282

Rating: 4.1 / 5 (62 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Corie Satterfield

Birthday: 1992-08-19

Address: 850 Benjamin Bridge, Dickinsonchester, CO 68572-0542

Phone: +26813599986666

Job: Sales Manager

Hobby: Table tennis, Soapmaking, Flower arranging, amateur radio, Rock climbing, scrapbook, Horseback riding

Introduction: My name is Corie Satterfield, I am a fancy, perfect, spotless, quaint, fantastic, funny, lucky person who loves writing and wants to share my knowledge and understanding with you.