HMAC Authentication Code Samples

HMAC Authentication Code Samples

Here we list code samples for generating the authentication header value for the HMAC-based schema in some common programming languages. Some modifications to the included code may be required, depending on the user’s system.

Java

import java.io.PrintStream;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Base64.Encoder;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
 
public class Main {
  public static void main(String[] args) {
    if (args.length != 2) {
      System.out.println("Usage: \"java -jar hmac <access-key> <secret-key>\"");
      return;
    }
    String isoDateTime = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT);
    System.out.println("isoDateTime: " + isoDateTime);
     
    String hmacKey = getHmacHash(args[1], isoDateTime + args[0]);
    System.out.println("api-key: " + args[0] + ":" + hmacKey);
  }
   
  private static String getHmacHash(String key, String data) {
    try {
      Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
      SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
      sha256_HMAC.init(secret_key);
      return Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
    }
    catch (Exception e) {
      System.out.println("Something went wrong signing the hmac key");
    }
    return null;
  }
} 

JavaScript

const ACCESS_KEY = <access-key>;
const SECRET_KEY = <secret_key>;
var timestamp = new Date().toISOString();
 
function getAuthHeader(secretKey, data) {
    var hmacDigest = determineAuthDigest(data, secretKey);
    var authHeader = ACCESS_KEY + ':' + hmacDigest;
    return authHeader;
}
function determineAuthDigest(data, secretKey){
    return CryptoJS.HmacSHA256(data, secretKey).toString(CryptoJS.enc.Base64);
}
var  authHeader  =  getAuthHeader(SECRET_KEY, timestamp + ACCESS_KEY );
console.log(“x-request-date:  “  +  timestamp);
console.log(“Authentication:  “  +  authHeader); 

C#

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace AuthenticationGeneration {
 class Program {
  static void Main(string[] args) {
   string ACCESS_KEY = "access";
   string SECRET_KEY = "secret";
   string timestamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
   if (args.Length > 2) {
    ACCESS_KEY = args[0];
    SECRET_KEY = args[1];
   }
   if (args.Length == 3) {
    timestamp = args[2];
   }
   Console.WriteLine("Authentication:" + getAuthHeader(timestamp, ACCESS_KEY, SECRET_KEY));
   Console.WriteLine("x-request-date:" + timestamp);
   Console.WriteLine("Press enter to close...");
   Console.ReadLine();
  }
  static string getAuthHeader(string timestamp, string access_key, string secretKey) {
   string plaintextSignature = timestamp + access_key;
   string hmacDigest = determineAuthDigest(plaintextSignature, secretKey);
   string authHeader = access_key + ":" + hmacDigest;
   return authHeader;
  }
  static string determineAuthDigest(string plaintextSignature, string secretKey) {
   var encoding = new System.Text.ASCIIEncoding();
   byte[] keyByte = encoding.GetBytes(secretKey);
   byte[] messageBytes = encoding.GetBytes(plaintextSignature);
   using(var hmacsha256 = new HMACSHA256(keyByte)) {
    byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
    return Convert.ToBase64String(hashmessage);
   }
  }
 }
} 

PHP

<?php
$ACCESS_KEY = 'access';
$SECRET_KEY = 'secret';
$timestamp = gmdate('Y-m-d\TH:i:s.v\Z187Z');
  
function getAuthHeader($accessKey, $timestamp, $secretKey)
    {
    $plaintextSignature = sprintf("%s%s", $timestamp, $accessKey);
    $hmacDigest = determineAuthDigest($plaintextSignature, $secretKey);
    $authHeader = sprintf("%s:%s:", $accessKey, $hmacDigest);
    return $authHeader;
    }
  
function determineAuthDigest($plaintextSignature, $secretkey)
    {
    return base64_encode(hash_hmac('sha256', $plaintextSignature, $secretkey, true));
    }
  
echo "\r\n";
$authHeader = getAuthHeader($ACCESS_KEY, $timestamp, $SECRET_KEY);
echo "Authorization: " . $authHeader;
echo "\r\n";
echo "x-request-date: " . $timestamp;
echo "\r\n"; 

Python

import hmac
import hashlib
import base64
import datetime
  
ACCESS_KEY = 'access_key'
SECRET_KEY = 'secret_key'
timestamp = datetime.datetime.utcnow().isoformat() + 'Z'
  
def getAuthHeader(access_key, timestamp, secretKey):
    plaintextSignature = timestamp + access_key
    hmacDigest = determineAuthDigest(plaintextSignature, secretKey)
    authHeader = access_key + ':' + hmacDigest
    return authHeader
  
def determineAuthDigest(plaintextSignature, secretKey):
    key_bytes = str.encode(secretKey, 'latin-1')
    data_bytes = str.encode(plaintextSignature, 'latin-1')
    dig = hmac.new(key_bytes, msg=data_bytes, digestmod=hashlib.sha256).digest()
    digest = base64.b64encode(dig).decode(); # py3k-mode
    return digest
  
print()
authHeader = getAuthHeader(ACCESS_KEY, timestamp, SECRET_KEY)
print("Authorization: " + authHeader)
print("x-request-date: " + timestamp)