AES Encryption in C#

Haider Ali Oct 12, 2023
  1. AES Encryption in C#
  2. Working on AES Encryption in C#
AES Encryption in C#

In this guide, we will learn about AES Encryption in C#.

AES Encryption in C#

The algorithm that we talk about is AES or Advanced Encryption Standard. This symmetrically encrypted algorithm grants both sender and receiver permission to use the same key to either encrypt the data or decrypt it.

This algorithm supports three-bit encryptions modes. 128, 192, and 256-bit encryptions.

AES helps us create an encrypted key and provides us with much-needed classes and functions to use. The government and private industries have tested advanced Encryption Standard (AES).

Working on AES Encryption in C#

The library System.Security.Cryptography is used for all the methods required to create an encrypted key. Now, let us discuss the classes used through this library, CryptoStream and MemoryStream.

CryptoStream stores any stream from the modes mentioned above. Any stream can be encrypted and decrypted if the compiler supports the mode.

The class MemoryStream is used when a class is storing streams to implement them. In this case, CryptoStream is in use, so MemoryStream will implement the stream.

The next class used is AesManaged, which manages the AES algorithm. The last and final class used is StreamWriter, it writes characters to a stream, so it is essential to use this class if we need to work with AES encryption.

Before we go to our code, it is important to use exception handling.

Code - main class:

using System;
using System.IO;
using System.Security.Cryptography;

namespace ConsoleApp1 {
  class Program {
    static void Main(string[] args) {
      Console.WriteLine("Write any string to encrypt: ");
      string text = Console.ReadLine();
      EncryptedDATA(text);  // write text to be encrypted
      Console.Read();
    }
  }
}

Code - function that takes the string input from the user:

static void EncryptedDATA(string TextToEncrypt) {
  try {
    using (AesManaged dataEncrypt = new AesManaged()) {
      byte[] TextEncrypted = Encrypt(TextToEncrypt, dataEncrypt.Key, dataEncrypt.IV);
      // passing the string data inside the Encrypt() function
      string myLine = $"the data encrypted is:{System.Text.Encoding.UTF8.GetString(TextEncrypted)}";
      Console.WriteLine(myLine);  // printing the encrypted data
    }
  } catch (Exception EX)  // exception handling
  {
    Console.WriteLine(EX.Message);
  }
}

Code - function that encrypts the data:

static byte[] Encrypt(string TextToEncrypt, byte[] encrypt, byte[] IV) {
  byte[] EncryptedText;
  using (AesManaged AESencrypt = new AesManaged())  // using a AesManaged function
  {
    ICryptoTransform DataEncrypt =
        AESencrypt.CreateEncryptor(encrypt, IV);      // here we are creating an encryptor
    using (MemoryStream memory = new MemoryStream())  // using a MemoryStream function
    {
      using (CryptoStream crypto = new CryptoStream(memory, DataEncrypt, CryptoStreamMode.Write))
      // using a CryptoStream function to store and write stream
      {
        {
          using (StreamWriter stream = new StreamWriter(crypto))
              stream.Write(TextToEncrypt);   // wrting stream
          EncryptedText = memory.ToArray();  // storing stream
        }
      }
    }
    return EncryptedText;
  }

Errors may appear while operating with AES encryption. To handle these errors, we use exception handling.

Full Source Code:

using System;
using System.IO;
using System.Security.Cryptography;

class Program {
  static void Main(string[] args) {
    Console.WriteLine("Write any string to encrypt: ");
    string text = Console.ReadLine();
    EncryptedDATA(text);  // write text to be encrypted
    Console.Read();
  }

  static void EncryptedDATA(string TextToEncrypt) {
    try {
      using (AesManaged dataEncrypt = new AesManaged()) {
        byte[] TextEncrypted = Encrypt(TextToEncrypt, dataEncrypt.Key, dataEncrypt.IV);
        // passing the string data inside the Encrypt() function
        string myLine =
            $"the data encrypted is: {System.Text.Encoding.UTF8.GetString(TextEncrypted)}";
        Console.WriteLine(myLine);  // printing the encrypted data
      }
    } catch (Exception EX)  // exception handling
    {
      Console.WriteLine(EX.Message);
    }
  }

  static byte[] Encrypt(string TextToEncrypt, byte[] encrypt, byte[] IV) {
    byte[] EncryptedText;
    using (AesManaged AESencrypt = new AesManaged())  // using a AesManaged function
    {
      ICryptoTransform DataEncrypt =
          AESencrypt.CreateEncryptor(encrypt, IV);      // here we are creating an encryptor
      using (MemoryStream memory = new MemoryStream())  // using a MemoryStream function
      {
        using (
            CryptoStream crypto = new CryptoStream(
                memory, DataEncrypt,
                CryptoStreamMode.Write))  // using a CryptoStream function to store and write stream
        {
          {
            using (StreamWriter stream = new StreamWriter(crypto))
                stream.Write(TextToEncrypt);   // wrting stream
            EncryptedText = memory.ToArray();  // storing stream
          }
        }
      }
      return EncryptedText;
    }
  }
}

Output:

Write any string to encrypt:
Hello
the data encrypted is: ??*?2?@???W@G?

The above code will encrypt any message. Once the data is encrypted, it can only be accessed by the user.

The way to read this data would be to decrypt it. Then and only will the data be visible.

Author: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn