using System.Security.Cryptography;
public static void Main()
AESGCMEncryptor ob=new AESGCMEncryptor();
string enctext=ob.Encrypt("eVIloWh9y5BdNWq0FBXiCrtJq5QteSJ4","Hello World");
Console.WriteLine("encrypted text-->"+enctext);
string plain=ob.Decrypt("eVIloWh9y5BdNWq0FBXiCrtJq5QteSJ4","B0McNWvIue6U8XZMzf6IvewpVUim");
Console.WriteLine("decrypt text-->"+plain);
public class AESGCMEncryptor
private const int GCM_IV_LENGTH = 12;
private const int GCM_TAG_LENGTH = 16;
public string Encrypt(string Key,string Plaintext)
byte[] key = Encoding.UTF8.GetBytes(Key);
string ivKey = Key.Substring(0, 12);
byte[] iv = Encoding.UTF8.GetBytes(ivKey);
byte[] plaintext = Encoding.UTF8.GetBytes(Plaintext);
using (AesGcm aesGcm = new AesGcm(key,16))
byte[] ciphertext = new byte[plaintext.Length];
byte[] tag = new byte[GCM_TAG_LENGTH];
aesGcm.Encrypt(iv, plaintext, ciphertext, tag);
byte[] result = new byte[ ciphertext.Length + GCM_TAG_LENGTH];
Array.Copy(ciphertext, 0, result, 0, ciphertext.Length);
Array.Copy(tag, 0, result, ciphertext.Length, GCM_TAG_LENGTH);
return Convert.ToBase64String(result);
public string Decrypt(string Key,string enctext)
byte[] key =Convert.FromBase64String(Key);
Console.WriteLine("Key== " +Key);
Console.WriteLine("Key length== " +key.Length);
byte[] cipherTextWithTag = Convert.FromBase64String(enctext);
string ivKey = Key.Substring(0, 16);
Console.WriteLine("ivKey== " +ivKey);
byte[] iv =Convert.FromBase64String(ivKey);
Console.WriteLine("ivKey length== " +iv.Length);
byte[] cipherText = new byte[cipherTextWithTag.Length - 16];
byte[] tag = new byte[16];
Console.WriteLine("cipherText length== " +cipherText.Length);
Console.WriteLine("tag length== " +tag.Length);
Array.Copy(cipherTextWithTag, 0, cipherText, 0, cipherTextWithTag.Length-16);
Array.Copy(cipherTextWithTag, cipherTextWithTag.Length-16, tag, 0, GCM_TAG_LENGTH);
using (AesGcm aesGcm = new AesGcm(key,16))
byte[] plainText = new byte[cipherTextWithTag.Length-16];
aesGcm.Decrypt(iv, cipherText, tag, plainText);
return Encoding.UTF8.GetString(plainText);
Console.WriteLine(ex.Message);