GCM mode Encryption and Decryption in ASP.NET Console App

Introduction

In this article, I have explained how to encrypt and decrypt the text using the AES Encryption standard using GCM mode.

Open Visual Studio, Create a new console application.

Home

Provide a project name, choose the location to store the information, and click next.

Configure new Project

Choose the .Net framework based on your project requirement, then click Create.

Additional information

Once the project has been created, then Right Click on the project name, choose to add, and click on the new item.

Add the class file to the existing project.

Code example

From the C# node, choose the class definition and provide the class file name like Encrypt_Decrypt_GCMfile.cs.

After we added the class file to our project solution.

Class

Once the class file is created successfully, we can write the Encryption and decryption methods in the class file.

Code example

Then we must install the NuGet package for GCM mode encryption and decryption.

Click the Tools tab and then select NuGet Package Manager. Click Manage NuGet packages for a solution.

Code example

Then browse for the" Portable.Bouncy.Castle" package and choose the project name, then click to install the Package and store it in the dependency file.

The portable bouncy castle helps create the GCM mode for encryption and decryption.

Additional information

Once the Package has been installed and the Class file has been created successfully, we can write the Encryption and decryption methods in the class file.

Additional information

Use the below code in a class file like Encrypt_Decrypt_GCMfile.cs.

Use the below code method to encrypt the given input text.

 public static string encrypt(string PlainText)
        {
      
            byte[] key=new byte[32];
                byte[] iv=new byte[16];
            string sR = string.Empty;
            
            try
            {
                byte[] plainBytes = Encoding.UTF8.GetBytes(PlainText);

                GcmBlockCipher cipher = new GcmBlockCipher(new AesFastEngine());
                AeadParameters parameters =
                             new AeadParameters(new KeyParameter(key), 128, iv, null);

                cipher.Init(true, parameters);

                byte[] encryptedBytes =
                       new byte[cipher.GetOutputSize(plainBytes.Length)];
                Int32 retLen = cipher.ProcessBytes
                               (plainBytes, 0, plainBytes.Length, encryptedBytes, 0);
                cipher.DoFinal(encryptedBytes, retLen);
                sR = Convert.ToBase64String
                     (encryptedBytes, Base64FormattingOptions.None);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            
            return sR;
        }

Use the below code method to decrypt the encrypted input text.

 public static string decrypt(string EncryptedText)
        {
            byte[] key = new byte[32];
            byte[] iv = new byte[16];
            string sR = string.Empty;
            try
            {
                byte[] encryptedBytes = Convert.FromBase64String(EncryptedText);

                GcmBlockCipher cipher = new GcmBlockCipher(new AesFastEngine());
                AeadParameters parameters =
                          new AeadParameters(new KeyParameter(key), 128, iv, null);
                //ParametersWithIV parameters = 
                //new ParametersWithIV(new KeyParameter(key), iv);

                cipher.Init(false, parameters);
                byte[] plainBytes =
                      new byte[cipher.GetOutputSize(encryptedBytes.Length)];
                Int32 retLen = cipher.ProcessBytes
                      (encryptedBytes, 0, encryptedBytes.Length, plainBytes, 0);
                cipher.DoFinal(plainBytes, retLen);

                sR = Encoding.UTF8.GetString(plainBytes).TrimEnd
                     ("\r\n\0".ToCharArray());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            return sR;
        }

The full code implementation is like in "Program.cs".

using System;
using System.Text;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System.Security.Cryptography;
using AES_GCM_block_change;
using Org.BouncyCastle.Utilities.Encoders;
using System.Security.Authentication;
using Org.BouncyCastle.Crypto.Tls;

namespace main
{
    namespace TestAES_GCM_256
    {
        class Program
        {

            public static void Main(string[] args)
            {
                while (true)
                {
                    ProcessEncryptDecrypt();
                }
            }
            public static void ProcessEncryptDecrypt()
            {
                int iChoice = 0;
                string strPwd = string.Empty;
                var encryptedString = string.Empty;
                Console.WriteLine("Enter your choice:");
                Console.WriteLine("1.Decryption   2.Encryption  3.Exit ");
                Console.WriteLine("******************************");
               
                iChoice = Convert.ToInt32(Console.ReadLine());
                



                if (iChoice == 1)
                {
                    Console.WriteLine("Enter the Password:");
                    
                    strPwd = Convert.ToString(Console.ReadLine());
                    encryptedString = AesGcm256.encrypt(strPwd);
                    Console.WriteLine($"encrypted string = {encryptedString}");


                }
                else if (iChoice == 2)
                {
                    Console.WriteLine("Enter the Password:");
                   strPwd = Convert.ToString(Console.ReadLine());
                    var decryptedString = AesGcm256.decrypt(strPwd);
                    Console.WriteLine($"decrypted string = {decryptedString}");
                }
                else
                {
                    Environment.Exit(0);
                }
            }
        }
    }

  
}

Once we ran the application, we got the output like the below screenshot.

Output

Happy Coding !...


Recommended Free Ebook
Similar Articles