Skip to content

Instantly share code, notes, and snippets.

@satyendrakumarsingh
Created August 19, 2022 12:55
Show Gist options
  • Save satyendrakumarsingh/c25fbd66cd82d320a614c07ceace4a43 to your computer and use it in GitHub Desktop.
Save satyendrakumarsingh/c25fbd66cd82d320a614c07ceace4a43 to your computer and use it in GitHub Desktop.
C# AES/GCM/NoPadding
using System;
using System.Text;
using System.Linq;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
/**
* Author: Satyendra Singh
* Created: 19-08-2022
* Description: Perform AES encryption based on pre-generated secret key and IV/Nonce.
*
* Disclaimer: This code is intended for demo purpose only, basis application need ensure implementation of error and exception handling.
*/
namespace AES.Class {
public class AESGCMUtility {
private const int KEY_BIT_SIZE = 256;
private const int MAC_BIT_SIZE = 128;
/// Encrypt method to encrypt message(plain-text) based on secret key and nonce
public static string encrypt(string message, string secretKey, string nonce) {
var plainText = Encoding.UTF8.GetBytes(message);
var decodedKey = hexStringToByteArray(secretKey);
var decodedNounce = hexStringToByteArray(nonce);
var cipherText = encrypt(plainText, decodedKey, decodedNounce);
return convertByteArrayToHexString(cipherText);
}
private static byte[] encrypt(byte[] text, byte[] key, byte[] nonce) {
var cipher = new GcmBlockCipher(new AesEngine());
var parameters = new AeadParameters(new KeyParameter(key), MAC_BIT_SIZE, nonce);
cipher.Init(true, parameters);
var cipherText = new byte[cipher.GetOutputSize(text.Length)];
var len = cipher.ProcessBytes(text, 0, text.Length, cipherText, 0);
cipher.DoFinal(cipherText, len);
return cipherText;
}
/// Convert HEX string into byte array.
private static byte[] hexStringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
/// Convert byte array into HEX string format.
private static string convertByteArrayToHexString(byte[] data) {
return BitConverter.ToString(data).Replace("-", string.Empty);
}
/// Demo code to call encrypt method.
public static void Main(string[] args) {
string value = encrypt("plain text message or data", "secret key in hex format", "nonce in hex format");
Console.WriteLine(value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment