using System.Security.Cryptography;
using System.Diagnostics;
static void Main(string[] args) {
Console.WriteLine("HERE");
UTF8Encoding utf8enc = new UTF8Encoding();
Console.OutputEncoding = utf8enc;
byte[] key = new byte[16];
byte[] nonce = new byte[12];
byte[] authTag = new byte[16];
byte[] authData = utf8enc.GetBytes("handy-auth-data");
AESData aesData = new AESData();
using(RandomNumberGenerator rng = RandomNumberGenerator.Create()) {
WriteByteArray("key", key);
WriteByteArray("nonce", nonce);
string plainText = "Hello AES/GCM!";
byte[] plainBytes = utf8enc.GetBytes(plainText);
WriteByteArray("plainBytes", plainBytes);
byte[] cipher = new byte[plainBytes.Length];
using(AesGcm aesgcm = new AesGcm(key)) aesgcm.Encrypt(nonce, plainBytes, cipher, authTag, authData);
WriteByteArray("cipher", cipher);
WriteByteArray("authTag", authTag);
aesData.nonce = System.Convert.ToBase64String(nonce);
aesData.cipher = System.Convert.ToBase64String(cipher);
aesData.authTag = System.Convert.ToBase64String(authTag);
aesData.authData = System.Convert.ToBase64String(authData);
Console.WriteLine("*** AES data ***");
Console.WriteLine("Key : {System.Convert.ToBase64String(key)}");
Console.WriteLine("Nonce : {aesData.nonce}");
Console.WriteLine("AuthTag : {aesData.authTag}");
Console.WriteLine("AuthData : {aesData.authData}");
Console.WriteLine("PlainText : {plainText}");
Console.WriteLine("EncryptedText : {aesData.cipher}");
nonce = System.Convert.FromBase64String(aesData.nonce);
cipher = System.Convert.FromBase64String(aesData.cipher);
authTag = System.Convert.FromBase64String(aesData.authTag);
authData = System.Convert.FromBase64String(aesData.authData);
byte[] decryptedBytes = new byte[cipher.Length];
using(AesGcm aesgcm = new AesGcm(key)) aesgcm.Decrypt(nonce, cipher, authTag, decryptedBytes, authData);
WriteByteArray("decryptedBytes", decryptedBytes);
string decryptedText = utf8enc.GetString(decryptedBytes);
Console.WriteLine("decryptedText = '{0}'", decryptedText);
static void WriteByteArray(string name, byte[] byteArray) {
Console.WriteLine("\"{0}\", {1} bytes, {2} bits:", name, byteArray.Length, byteArray.Length << 3);