Request signature in Python 3

This article presents a sample implementation of a request signature in Python 3.

# Dependencies

This example uses the hmac, hashlib, json and urllib.parse core dependencies from Python 3.

# Example

The following simple example implements the algorithm described in the Request signature guide. The most important thing is to use the hmac module with the appropriate SHA256 algorithm and provide the parameters in the correct order: method, url, timestamp, body.

The method parameter should be uppercase and path should contain only the relative path and query parameters from the URL, not the full URL address. The full URL address should be converted to e.g. /webhook?a=1.

If the algorithm works correctly, it should generate the same signature as the one given below: 56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762 for the following parameters:

  • apiSecret=SECRET

  • method=POST

  • uri=http://demo.example.com/webhook?a=1

  • timestamp=1563276169752

  • body={a:1}

import hmac
import hashlib
import json
import urllib.parse

def hmacDigest(data, key):
    keyEncoded = key.encode()
    dataEncoded = data.encode()

    h = hmac.new(keyEncoded, dataEncoded, hashlib.sha256)

    return h.hexdigest()


def generateSignature(apiSecret, method, uri, timestamp, body):
    url = urllib.parse.urlparse(uri)
    path = url.path

    if (url.query):
        path = path + "?" + url.query

    methodUpperCase = method.upper()
    data = methodUpperCase + path + str(timestamp)

    if (body):
        data += json.dumps(body, separators=(',',':'))

    return hmacDigest(data, apiSecret)


expectedSignature = "56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762"
generatedSignature = generateSignature(
    "SECRET",
    "POST",
    "http://demo.example.com/webhook?a=1",
     1563276169752,
    {"a": 1}
)

print(generatedSignature == expectedSignature)

# Usage

Run:

python3 index.py