Generate HMACs with different algorithms (Python3)

Various services require a token to be submitted using a HMAC. Although SHA1-HMAC is common, other hashing algorithms are sometimes required. This Python 3 snippet allows you to specify the hashing algorithm to use

Similar To

Details

  • Language: Python3

Snippet

import hashlib
import hmac

def createHMAC(signstr,secret,algo):
    ''' Create a HMAC of signstr using secret and algo
    '''
    hashedver = hmac.new(secret.encode('utf-8'),signstr.encode('utf-8'),algo)
    return hashedver.hexdigest()

Usage Example

>>> createHMAC('Sign this string','MySecret',hashlib.sha1)
'ef20b522a7c55c8392a2c9916c6ba0fe81637f54'
>>> createHMAC('Sign this string','MySecret',hashlib.sha256)
'aedb0bc595d01a7f795ff43dd72e0710926903f914bc969633d594e32e4a9c7c'
>>> createHMAC('Sign this string','MySecret',hashlib.sha512)
'6c24b52a1ba9ed559b6f7742abb498e37233d41e25d18111db75549f947301a035b632d982736702cfa67549a2d68aa5455ee1807e637094b85ed0021f6f2787'