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?
This module implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA's MD5 algorithm (defined in internet RFC 1321).
Python has a built-in library, hashlib , that is designed to provide a common interface to different secure hashing algorithms. The module provides constructor methods for each type of hash. For example, the . sha256() constructor is used to create a SHA256 hash.
Hashlib is a Python library that provides the SHA-224, SHA-256, SHA-384, SHA-512 hash algorithms. Besides this Hashlib provides the platform optimized versions of MD5 and SHA1.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With