Examples of backend HMAC computation

This article contains examples of HMAC computation used for the User identity verification feature for various backend languages.

HMAC expiration note

Those examples are about HMAC computation for the first load. If you want to use the HMAC expiration feature, you are responsible for renewing the HMAC code and passing it to Product Fruits via the identityUser method.

NodeJS

const crypto = require('crypto');
​​
//// PROPS /////
var username = "testUser" // Your real username after authentication
var secret = "SecretkeyFromWorkspaceSettings"
var expiration_minutes = 0; // keep to 0 if you don't want to use the expiration feature
////////////////
​
var date = new Date();
​
var serialisedDate = "";
​
if (expiration_minutes > 0) {
    date.setMinutes(date.getMinutes() + expiration_minutes)
​    serialisedDate = date.toJSON()
}
​
var hmacData = `${username}${serialisedDate}`
​
var hmacHash = crypto
    .createHmac("sha256", secret)
    .update(hmacData)
    .digest("Base64");
​
const hmacInfo = {
    hash: hmacHash,
    expiration: expiration_minutes > 0 ? date.toJSON() : null
};
​
console.log(hmacInfo)

.NET

The example uses C#.

using System.Text;
using System.Security.Cryptography;
​
string username = "testUser"; // Your real username after authentication
string secret = "SecretkeyFromWorkspaceSettings";
int expiration_m = 0; // set to 0 if you don't want to use the expiration
​
string expiration = expiration_m > 0 ? DateTime.UtcNow.AddMinutes(expiration_m).ToString("o"): "";
​
string data = string.Format("{0}{1}", username, expiration ?? "");
​
var secretBytesArr = Encoding.ASCII.GetBytes(secret);
​
using var hmacsha256 = new HMACSHA256(secretBytesArr);
​
byte[] hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(data));
​
string hashString = Convert.ToBase64String(hash);
​
System.Console.WriteLine(expiration);
System.Console.WriteLine(hashString);

Java

import java.util.Base64;
import javax.crypto.Mac;
import java.time.Instant;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
​
public class Main {
​
    /**
     * @param args
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws UnsupportedEncodingException
     */
    public static void main(String[] args)
            throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        
        //// PROPS /////
        String username = "testUser"; // Your real username after authentication
        String secretKey = "SecretkeyFromWorkspaceSettings";
        String algorithm = "HmacSHA256";
        int expiration_seconds = 0; // set to 0 to disable the expiration feature
​
        String expiration = expiration_seconds > 0 ? Instant.now().plusSeconds(expiration_seconds).toString() : ""; // Example UTC expiration date-time -> 2023-08-30T13:08:48.389Z
​
        // data = concat username with exiration UTC string
        String data = username + expiration;
​
        Mac sha256_HMAC = Mac.getInstance(algorithm);
        SecretKeySpec secret_key = new SecretKeySpec(secretKey.getBytes(), algorithm);
        sha256_HMAC.init(secret_key);
        var hash = sha256_HMAC.doFinal(data.getBytes());
​
        byte[] encoded = Base64.getEncoder().encode(hash);
        String hashStr = new String(encoded);
​
        System.out.println(hashStr);
    }
}

PHP

<?php
​
//// PROPS /////
$username = "testUser"; // Your real username after authentication
$secret = "SecretkeyFromWorkspaceSettings";
$expiration_minutes = 0; // set to 0 if you don't want to use the expiration feature
///////////////////////////////////
​
$date_utc = new \DateTime("now", new \DateTimeZone("UTC"));
​
$expiration = "";
​
if ($expiration_minutes > 0) {
    $expiration  = $date_utc->add(new DateInterval('PT' . $expiration_minutes . 'M'))->format('Y-m-d\TH:i:s\Z');;
}
​
$data = $username . $expiration;
​
$hashBin = hash_hmac('sha256', $data, $secret, true);
​
$hash = base64_encode($hashBin);
​
echo $expirations;
echo $hash;