Generate HMACs with different algorithms



Published: 2019-10-02 11:45:53 +0000
Categories: Python3,

Language

Python3

Description

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

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'


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

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

python3 -c 'import hashlib,sys,hmac; h=hmac.new(sys.argv[1].encode("utf-8"),sys.argv[2].encode("utf-8"),getattr(hashlib,sys.argv[3])); print(h.hexdigest())' "MySecret" "Sign this string" sha256
aedb0bc595d01a7f795ff43dd72e0710926903f914bc969633d594e32e4a9c7c

python3 -c 'import hashlib,sys,hmac; h=hmac.new(sys.argv[1].encode("utf-8"),sys.argv[2].encode("utf-8"),getattr(hashlib,sys.argv[3])); print(h.hexdigest())' "MySecret" "Sign this string" sha512
6c24b52a1ba9ed559b6f7742abb498e37233d41e25d18111db75549f947301a035b632d982736702cfa67549a2d68aa5455ee1807e637094b85ed0021f6f2787

Keywords

hmac, python, python3,

Latest Posts


Copyright © 2019 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, yr4pnhounvdybotb.onion and snippets.6zdgh5a5e6zpchdz.onion