using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
public class AesGcmExample
public static void Main(string[] args)
string plaintext = "This is a secret message.";
byte[] key = GenerateRandomKey(256);
byte[] iv = GenerateRandomIV();
byte[] associatedData = Encoding.UTF8.GetBytes("Associated Data");
byte[] ciphertext = Encrypt(plaintext, key, iv, associatedData);
string decryptedText = Decrypt(ciphertext, key, iv, associatedData);
Console.WriteLine("Plaintext: " + plaintext);
Console.WriteLine("Ciphertext: " + Convert.ToBase64String(ciphertext));
Console.WriteLine("Decrypted Text: " + decryptedText);
public static byte[] Encrypt(string plaintext, byte[] key, byte[] iv, byte[] associatedData)
GcmBlockCipher cipher = new GcmBlockCipher(new AesEngine());
AeadParameters parameters = new AeadParameters(new KeyParameter(key), 128, iv, associatedData);
cipher.Init(true, parameters);
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
byte[] ciphertext = new byte[cipher.GetOutputSize(plaintextBytes.Length)];
int len = cipher.ProcessBytes(plaintextBytes, 0, plaintextBytes.Length, ciphertext, 0);
cipher.DoFinal(ciphertext, len);
Console.WriteLine("Encryption error: " + ex.Message);
public static string Decrypt(byte[] ciphertext, byte[] key, byte[] iv, byte[] associatedData)
GcmBlockCipher cipher = new GcmBlockCipher(new AesEngine());
AeadParameters parameters = new AeadParameters(new KeyParameter(key), 128, iv, associatedData);
cipher.Init(false, parameters);
byte[] plaintext = new byte[cipher.GetOutputSize(ciphertext.Length)];
int len = cipher.ProcessBytes(ciphertext, 0, ciphertext.Length, plaintext, 0);
cipher.DoFinal(plaintext, len);
return Encoding.UTF8.GetString(plaintext, 0, len);
Console.WriteLine("Decryption error: " + ex.Message);
public static byte[] GenerateRandomKey(int keySize)
SecureRandom random = new SecureRandom();
byte[] key = new byte[keySize / 8];
public static byte[] GenerateRandomIV()
SecureRandom random = new SecureRandom();
byte[] iv = new byte[12];