Saturday, October 30, 2021

AES Encryption In C#

 .NET provides high 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 block size.
 
AesManaged class is a managed implementation of the AES algorithm. This article demonstrates how to 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,
  1. AesManaged aes = new AesManaged();  
Step 2

Create Encryptor,
  1. ICryptoTransform encryptor = aes.CreateEncryptor(Key, IV);  
Step 3

Create MemoryStream,
  1. MemoryStream ms = new MemoryStream();  
Step 4

Create CryptoStream from MemoryStream and Encrypter and write it.
  1. using(CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))   
  2. {  
  3.     // Create StreamWriter and write data to a stream    
  4.     using(StreamWriter sw = new StreamWriter(cs))  
  5.     sw.Write(plainText);  
  6.     encrypted = ms.ToArray();  
  7. }  
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. 
  1. using System;  
  2. using System.IO;  
  3. using System.Security.Cryptography;  
  4. class ManagedAesSample {  
  5.     public static void Main() {  
  6.         Console.WriteLine("Enter text that needs to be encrypted..");  
  7.         string data = Console.ReadLine();  
  8.         EncryptAesManaged(data);  
  9.         Console.ReadLine();  
  10.     }  
  11.     static void EncryptAesManaged(string raw) {  
  12.         try {  
  13.             // Create Aes that generates a new key and initialization vector (IV).    
  14.             // Same key must be used in encryption and decryption    
  15.             using(AesManaged aes = new AesManaged()) {  
  16.                 // Encrypt string    
  17.                 byte[] encrypted = Encrypt(raw, aes.Key, aes.IV);  
  18.                 // Print encrypted string    
  19.                 Console.WriteLine($ "Encrypted data: {System.Text.Encoding.UTF8.GetString(encrypted)}");  
  20.                 // Decrypt the bytes to a string.    
  21.                 string decrypted = Decrypt(encrypted, aes.Key, aes.IV);  
  22.                 // Print decrypted string. It should be same as raw data    
  23.                 Console.WriteLine($ "Decrypted data: {decrypted}");  
  24.             }  
  25.         } catch (Exception exp) {  
  26.             Console.WriteLine(exp.Message);  
  27.         }  
  28.         Console.ReadKey();  
  29.     }  
  30.     static byte[] Encrypt(string plainText, byte[] Key, byte[] IV) {  
  31.         byte[] encrypted;  
  32.         // Create a new AesManaged.    
  33.         using(AesManaged aes = new AesManaged()) {  
  34.             // Create encryptor    
  35.             ICryptoTransform encryptor = aes.CreateEncryptor(Key, IV);  
  36.             // Create MemoryStream    
  37.             using(MemoryStream ms = new MemoryStream()) {  
  38.                 // Create crypto stream using the CryptoStream class. This class is the key to encryption    
  39.                 // and encrypts and decrypts data from any given stream. In this case, we will pass a memory stream    
  40.                 // to encrypt    
  41.                 using(CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) {  
  42.                     // Create StreamWriter and write data to a stream    
  43.                     using(StreamWriter sw = new StreamWriter(cs))  
  44.                     sw.Write(plainText);  
  45.                     encrypted = ms.ToArray();  
  46.                 }  
  47.             }  
  48.         }  
  49.         // Return encrypted data    
  50.         return encrypted;  
  51.     }  
  52.     static string Decrypt(byte[] cipherText, byte[] Key, byte[] IV) {  
  53.         string plaintext = null;  
  54.         // Create AesManaged    
  55.         using(AesManaged aes = new AesManaged()) {  
  56.             // Create a decryptor    
  57.             ICryptoTransform decryptor = aes.CreateDecryptor(Key, IV);  
  58.             // Create the streams used for decryption.    
  59.             using(MemoryStream ms = new MemoryStream(cipherText)) {  
  60.                 // Create crypto stream    
  61.                 using(CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) {  
  62.                     // Read crypto stream    
  63.                     using(StreamReader reader = new StreamReader(cs))  
  64.                     plaintext = reader.ReadToEnd();  
  65.                 }  
  66.             }  
  67.         }  
  68.         return plaintext;  
  69.     }  
  70. }  
Listing 1.
 
The output looks like the following where you can type any text that will be encrypted and decrypted.
 
AES Encryption 
 
References
  • https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  • https://docs.microsoft.com

No comments:

Post a Comment

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...