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

Remotely backing up PFsense Configuration (BASH)
FFMPEG: Converting RMVB to X264 MP4 (BASH)
Recursively print table (print_r equivalent) (LUA)
Bulk Delete Comments from (Self-Hosted) JIRA Issues (Misc)
Add a static entry to the ARP table (BASH)
SSL Cipher Hex codes to Human Readable Names (Misc)
Convert Ascii to Binary (BASH)
Intercepting Outbound DNS Queries (BASH)
Handle Google Verification files within NGinx Configuration (NGinx)
Getting WhatsApp Rich Snippet Previews Working (Misc)

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