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.