HMAC Examples

Data and code examples for AuricVault®-compliant HMAC generation.

  • Encode the generated HMAC as hexadecimal.

  • Force the encoded hexadecimal to lowercase.

  • A hexadecimal-encoded SHA512 HMAC is always 128 characters long.

Sample Input

Input
secret: vQrHr8%1Dvr5HQ9nv8jGew*y5*UpH7br
payload: Sample Payload. Always calculate the HMAC based on a string, not a JSON structure.
Output Snippet (first and last 10 characters)
bcd9121b58.....a3efcdc3c2

C#

using System;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;


namespace HMACSHA256Example
{

    class Program
    {
        private static byte[] StringEncode(string text)
        {
            var encoding = new ASCIIEncoding();
            return encoding.GetBytes(text);
        }

        private static byte[] HashHMAC(byte[] key, byte[] message)
        {
            var hash = new HMACSHA512(key);
            return hash.ComputeHash(message);
        }

        private static string HexEncode(byte[] theBytes)
        {
            return BitConverter.ToString(theBytes).Replace("-", "").ToLower();
        }

        static void Main(string[] args)
        {
            var secret = "vQrHr8%1Dvr5HQ9nv8jGew*y5*UpH7br";
            var message = "Sample Payload. Always calculate the HMAC based on a string, not a JSON structure.";
            var signature = HashHMAC(
                    StringEncode(secret),
                    StringEncode(message)
                    );
            var auricHmacString = HexEncode(signature);
            Console.WriteLine(auricHmacString);
        }
    }
}

NodeJS

var crypto = require('crypto');
var hash = crypto.createHmac('sha512', secret);
hash.update(payload);

// Hex digest is lowercase.
var the_hmac = hash.digest('hex');

PHP

// Default output is hexadecimal.
$hmac = hash_hmac('sha512', $payload, $secret);

Python

import hashlib
import hmac

def calc_hmac(payload, secret):
    calculated_hmac = hmac.new(
        secret.encode("utf-8"),
        payload.encode("utf-8"),
        hashlib.sha512).hexdigest()
    return calculated_hmac.lower()