using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System.Security.Cryptography;
namespace TestAES_GCM_256
public static void Main()
string passphrase = "this-is-a-test-passphrase";
string inputData = "94b681ef29d9a6d7-e6fa36c4c00977de1745fc63-a1ad0481bdbeeaa02c013a2dce82520ddd762355e18f1e2f20c0ea9d001ece24e9b8216ed4b9c6a06e1ef34c953f80";
string[] arr = inputData.Split('-');
byte[] salt = Convert.FromHexString(arr[0]);
byte[] iv = Convert.FromHexString(arr[1]);
byte[] data = Convert.FromHexString(arr[2]);
byte[] key = GetPbkdf2Bytes(passphrase, salt, 1000, 32);
decrypt(arr[2], key, iv);
private static byte[] GetPbkdf2Bytes(string password, byte[] salt, int iterations, int outputBytes)
var pbkdf2 = new Rfc2898DeriveBytes(password, salt);
pbkdf2.IterationCount = iterations;
return pbkdf2.GetBytes(outputBytes);
private static readonly SecureRandom Random = new SecureRandom();
public static readonly int NonceBitSize = 128;
public static readonly int MacBitSize = 128;
public static readonly int KeyBitSize = 256;
public static byte[] NewKey()
var key = new byte[KeyBitSize / 8];
public static byte[] NewIv()
var iv = new byte[NonceBitSize / 8];
public static Byte[] HexToByte(string hexStr)
byte[] bArray = new byte[hexStr.Length / 2];
for (int i = 0; i < (hexStr.Length / 2); i++)
byte firstNibble = Byte.Parse(hexStr.Substring((2 * i), 1),
System.Globalization.NumberStyles.HexNumber);
byte secondNibble = Byte.Parse(hexStr.Substring((2 * i) + 1, 1),
System.Globalization.NumberStyles.HexNumber);
int finalByte = (secondNibble) | (firstNibble << 4);
bArray[i] = (byte)finalByte;
public static string toHex(byte[] data)
string hex = string.Empty;
public static string toHex(string asciiString)
string hex = string.Empty;
foreach (char c in asciiString)
hex += string.Format("{0:x2}", System.Convert.ToUInt32(tmp.ToString()));
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
public static string decrypt(string EncryptedText, byte[] key, byte[] iv)
string sR = string.Empty;
byte[] encryptedBytes = Convert.FromHexString(EncryptedText);
GcmBlockCipher cipher = new GcmBlockCipher(new AesEngine());
AeadParameters parameters =
new AeadParameters(new KeyParameter(key), 128, iv, null);
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());
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);