Skip to content

Instantly share code, notes, and snippets.

@satyendrakumarsingh
Created August 19, 2022 12:52
Show Gist options
  • Save satyendrakumarsingh/b9dd7674c36e8d41bc26c149c174f4eb to your computer and use it in GitHub Desktop.
Save satyendrakumarsingh/b9dd7674c36e8d41bc26c149c174f4eb to your computer and use it in GitHub Desktop.
C# HMAC SHA512
using System;
using System.Text;
using System.Linq;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Parameters;
/**
* Author: Satyendra Singh
* Created: 19-08-2022
* Description: Calculate HMACSHA512 based on pre-generated secret key.
*
* Disclaimer: This code is intended for demo purpose only, basis application need ensure implementation of error and exception handling.
*/
namespace HMAC.Class {
public class HMACUtility {
public static string generateHmac(string text, string key) {
var hmac = new HMac(new Sha512Digest());
hmac.Init(new KeyParameter(hexStringToByteArray(key)));
byte[] result = new byte[hmac.GetMacSize()];
byte[] bytes = Encoding.UTF8.GetBytes(text);
hmac.BlockUpdate(bytes, 0, bytes.Length);
hmac.DoFinal(result, 0);
return System.Convert.ToBase64String(result);
}
/// 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();
}
/// Demo code to call generateHmac method.
public static void Main(string[] args) {
string value = generateHmac("message", "secret key in hex");
Console.WriteLine(value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment