Implementation
The following pseudocode demonstrates how HMAC may be implemented. Blocksize is 64 (bytes) when using one of the following hash functions: SHA-1, MD5, RIPEMD-128/160.
function hmac (key, message) if (length(key) > blocksize) then key = hash(key) // keys longer than blocksize are shortened end if if (length(key) < blocksize) then key = key ∥ // keys shorter than blocksize are zero-padded ('∥' is concatenation) end if o_key_pad = ⊕ key // Where blocksize is that of the underlying hash function i_key_pad = ⊕ key // Where ⊕ is exclusive or (XOR) return hash(o_key_pad ∥ hash(i_key_pad ∥ message)) // Where '∥' is concatenation end functionThe following is a Python implementation of 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 # 80070713463e7749b90c2dc24911e275Read more about this topic: Hash-based Message Authentication Code
Related Phrases
Related Words