Generating a SHA-1 HMAC in Python

When signing a message posted to an API, sometimes an SHA1 digest or hash is required. This example shows the signing of a payload, and insertion of an X-Hmac header – however you may need to modify this depending on the API you are using.

def make_digest(message, key):
    key     = bytes(key, 'UTF-8')
    message = bytes(message, 'UTF-8')

    digester = hmac.new(key, message, hashlib.sha1)
    sig = digester.hexdigest()
    return sig

The below shows an example API call against the Genband API, this shows the JSON payload being signed.

#!/usr/bin/python3
from requests import Session
import hmac
import hashlib
import json


def make_digest(message, key):
    key     = bytes(key, 'UTF-8')
    message = bytes(message, 'UTF-8')

    digester = hmac.new(key, message, hashlib.sha1)
    sig = digester.hexdigest()
    return sig


s = Session()

base_api_url = "https://portal-sandbox.genband.com:443/api/rest/3.42/"
json_payload = "{}"
hmac_key = 'key-goes-here'
digest = make_digest(json_payload, hmac_key)

headers = {
        'X-Group-ID'    : 'group-id',
        'X-User-ID'     : 'user-id',
        'X-User-Token'  : 'token-here',
        'X-Hmac'         : digest
}

url = base_api_url + "path/to/method"
ret = s.get(url, headers=headers, json={})

Below shows the generation in PHP

<?php

$key = 'your-secure-key-here';
$payload = '{}';

echo hash_hmac('sha1', $payload, $key);