Generating HMACs with different hashing algorithms (Python)

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

Similar To

Details

  • Language: Python

Snippet

import hashlib            
import hmac

def createHMAC(signstr,secret,algo):
    ''' Create a HMAC of signstr using secret and algo
    '''
    hashedver = hmac.new(secret,signstr,algo)
    return hashedver.digest().encode('hex')

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'

`# Or as a Python one-liner to run from BASH
python -c 'import hashlib,sys,hmac; h=hmac.new(sys.argv[1],sys.argv[2],getattr(hashlib,sys.argv[3])); print h.digest().encode("hex")'\
 $secret $string $algo

# Example:
python -c 'import hashlib,sys,hmac; h=hmac.new(sys.argv[1],sys.argv[2],getattr(hashlib,sys.argv[3])); print h.digest().encode("hex")'\
 "MySecret" "Sign this string" sha1
ef20b522a7c55c8392a2c9916c6ba0fe81637f54

python -c 'import hashlib,sys,hmac; h=hmac.new(sys.argv[1],sys.argv[2],getattr(hashlib,sys.argv[3])); print h.digest().encode("hex")'\
 "MySecret" "Sign this string" sha256
aedb0bc595d01a7f795ff43dd72e0710926903f914bc969633d594e32e4a9c7c

python -c 'import hashlib,sys,hmac; h=hmac.new(sys.argv[1],sys.argv[2],getattr(hashlib,sys.argv[3])); print h.digest().encode("hex")'\
 "MySecret" "Sign this string" sha512
6c24b52a1ba9ed559b6f7742abb498e37233d41e25d18111db75549f947301a035b632d982736702cfa67549a2d68aa5455ee1807e637094b85ed0021f6f2787`