Skip to content

Instantly share code, notes, and snippets.

@gthomas
Created August 24, 2012 16:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gthomas/3452673 to your computer and use it in GitHub Desktop.
Save gthomas/3452673 to your computer and use it in GitHub Desktop.
Python HMAC md5
#!/usr/bin/env python
from hashlib import md5
trans_5C = "".join(chr(x ^ 0x5c) for x in xrange(256))
trans_36 = "".join(chr(x ^ 0x36) for x in xrange(256))
blocksize = md5().block_size
def hmac_md5(key, msg):
if len(key) > blocksize:
key = md5(key).digest()
key += chr(0) * (blocksize - len(key))
o_key_pad = key.translate(trans_5C)
i_key_pad = key.translate(trans_36)
return md5(o_key_pad + md5(i_key_pad + msg).digest())
if __name__ == "__main__":
h = hmac_md5("key", "The quick brown fox jumps over the lazy dog")
print h.hexdigest() # 80070713463e7749b90c2dc24911e275
@cdpath
Copy link

cdpath commented Oct 30, 2018

or just use hmac in py3

import hmac
def hmac_md5(key, s):
    return hmac.new(key.encode('utf-8'), s.encode('utf-8'), 'MD5').hexdigest()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment