Skip to content

Instantly share code, notes, and snippets.

@cajuncoding
Last active April 23, 2024 03:52
Show Gist options
  • Save cajuncoding/a1da239e4ee1dac56f4e4cafbcad5291 to your computer and use it in GitHub Desktop.
Save cajuncoding/a1da239e4ee1dac56f4e4cafbcad5291 to your computer and use it in GitHub Desktop.
Simple Class to create a well formed HMAC with SHA256 encryption and HEX Encoding
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace CajunCoding.HMAC
{
/// <summary>
/// BBernard / CajunCoding
/// A simple class to generate HMAC codes (hash-based message authentication code) to be used for signing and validating
/// authenticity & integrity of messages between systems. More Info: https://en.wikipedia.org/wiki/HMAC
/// </summary>
public static class HMACGenerator
{
/// <summary>
/// Generates a valid HMAC using SHA-256 Encryption with HEX Encoding for transport as a string.
/// </summary>
/// <param name="encryptionKey">The shared secret string key used to generate the HMAC.</param>
/// <param name="value">The value to be hashed.</param>
/// <returns></returns>
public static string ComputeSha256HexEncodedHash(string encryptionKey, string value)
{
if (string.IsNullOrWhiteSpace(encryptionKey)) throw new ArgumentNullException(nameof(encryptionKey));
if (string.IsNullOrWhiteSpace(value)) throw new ArgumentNullException(nameof(value));
var encryptionKeyBytes = Encoding.UTF8.GetBytes(encryptionKey);
using (var hashAlgorithm = new HMACSHA256(encryptionKeyBytes))
{
var valueBytes = Encoding.UTF8.GetBytes(value);
var hashBytes = hashAlgorithm.ComputeHash(valueBytes);
var hashString = hashBytes.ToHexString();
return hashString;
}
}
public static string ToHexString(this byte[] bytes)
{
#if NET5_0_OR_GREATER
return Convert.ToHexString(bytes);
#else
return string.Concat(bytes.Select(b => ((int)b).ToString("x2")));
#endif
}
}
}
@cajuncoding
Copy link
Author

cajuncoding commented Jun 7, 2023

This is useful for signing and validating authenticity & integrity of messages between systems.

Real World Use Case Example:
When integrating with Intercom to enable Identity verification, they provide a secret signing key and require a well formed HMAC (hash of the User ID or Email) be created with SHA256 encryption & HEX encoding. This class provides the correct implementation for this kind of signing in C#.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment