Generating HMACs with different hashing algorithms



Published: 2018-04-12 09:06:52 +0000
Categories: Python,

Language

Python

Description

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

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


Keywords

HMAC, generate, hashed message authentication code, create, build,

Latest Posts

Urldecode string (LUA)
FFMPEG Convert YUV444p to YUV420p (BASH)
Forcing FFMPEG to honour segment length in HLS Stream Creator (BASH)
Force CURL to place request to a specific IP (BASH)
Set a variable only if it is undefined (Javascript)
Ignore query string with Nginx caching proxy (NGinx)
Get breakdown of UK and non-UK votes for a Parliamentary Petition (Python)
Decompress Mozilla Firefox jsonlz4 bookmark backup files (Python)
Setting Git author details for a single repo (Git)
Checking Virtual Machine Resource Allocations with Libvirt (BASH)

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