Why the hashlib and hmac are generating different hash values?

Er Dj picture Er Dj · Aug 4, 2011 · Viewed 14.1k times · Source

In Python 2.7,

my = "my"
key = "key"
print(hashlib.sha256(my + key).hexdigest())
print(hmac.new(my, key, hashlib.sha256).hexdigest())

output,

5e50f405ace6cbdf17379f4b9f2b0c9f4144c5e380ea0b9298cb02ebd8ffe511
15a55993a27e0de7a4c4daa67a7c219199a464ca283797f545b783cce07b38a5

or have I misunderstood?

Answer

mdeous picture mdeous · Aug 4, 2011

This is because hmac uses the provided key to generate a salt and make the hash more strong, while hashlib only hashes the provided message.

By looking at the hmac module source code, you will find how to achieve the same behaviour as hmac using the hashlib module, here the used algorithm (it's not the original one, i stripped some checkings to have just the interesting part):

import hashlib

MESSAGE = "msg"
KEY = "key"

trans_5C = "".join ([chr (x ^ 0x5C) for x in xrange(256)])
trans_36 = "".join ([chr (x ^ 0x36) for x in xrange(256)])

outer = hashlib.sha256()
inner = hashlib.sha256()

KEY = KEY + chr(0) * (inner.block_size - len(KEY))

outer.update(KEY.translate(trans_5C))
inner.update(KEY.translate(trans_36))
inner.update(MESSAGE)
outer.update(inner.digest())

result = outer.hexdigest()
print result # prints 2d93cbc1be167bcb1637a4a23cbff01a7878f0c50ee833954ea5221bb1b8c628

The same directly using hmac:

import hashlib
import hmac

result = hmac.new(KEY, MESSAGE, hashlib.sha256).hexdigest()
print result # prints 2d93cbc1be167bcb1637a4a23cbff01a7878f0c50ee833954ea5221bb1b8c628

So when using hmac, it doesn't only hashes the given message using the specified hashing algorithm, it also uses the key to complexify the hash.