using System.Buffers.Binary;
using System.Security.Cryptography;
public static class Program
public static void Main()
string password = "com.arteffect0031.0xxxxxxxxxxxxx";
using var aesObj = new AesGcmService(password);
Console.WriteLine($"Plain: \"{plain}\"");
string enc = "XFpveqewotKNLc9U+tKCDwVPQJRVxubrU8svhlajBNc=";
Console.WriteLine($"Encrypted: \"{enc}\"");
string dec = aesObj.Decrypt(enc);
Console.WriteLine($"Decrypted: \"{dec}\"");
public class AesGcmService : IDisposable
private readonly AesGcm _aes;
public AesGcmService(string password)
byte[] key = new Rfc2898DeriveBytes(password, new byte[8], 1000).GetBytes(32);
public string Encrypt(string plain)
byte[] plainBytes = Encoding.UTF8.GetBytes(plain);
int cipherSize = plainBytes.Length;
int encryptedDataLength = nonceSize + cipherSize+ tagSize;
Span<byte> encryptedData = encryptedDataLength < 1024 ? stackalloc byte[encryptedDataLength] : new byte[encryptedDataLength].AsSpan();
var nonce = encryptedData.Slice(0, nonceSize);
var tag = encryptedData.Slice(nonceSize+cipherSize, tagSize);
var cipherBytes = encryptedData.Slice(nonceSize, cipherSize);
RandomNumberGenerator.Fill(nonce);
_aes.Encrypt(nonce, plainBytes.AsSpan(), cipherBytes, tag);
return Convert.ToBase64String(encryptedData);
public string Decrypt(string cipher)
Span<byte> encryptedData = Convert.FromBase64String(cipher).AsSpan();
int cipherSize = encryptedData.Length - nonceSize - tagSize;
var nonce = encryptedData.Slice(0, nonceSize);
var tag = encryptedData.Slice(nonceSize+cipherSize, tagSize);
var cipherBytes = encryptedData.Slice(nonceSize, cipherSize);
Span<byte> plainBytes = cipherSize < 1024 ? stackalloc byte[cipherSize] : new byte[cipherSize];
_aes.Decrypt(nonce, cipherBytes, tag, plainBytes);
return Encoding.UTF8.GetString(plainBytes);