HMAC (Hash-based Message Authentication Code) is a MAC defined in RFC2104 and FIPS-198 and constructed using a cryptographic hash algorithm.
It is usually named HMAC-X, where X is the hash algorithm; for instance HMAC-SHA1 or HMAC-SHA256.
The strength of an HMAC depends on:
- the strength of the hash algorithm
- the entropy of the secret key
This is an example showing how to generate a MAC (with HMAC-SHA256):
>>> from Crypto.Hash import HMAC, SHA256 >>> >>> secret = b'Swordfish' >>> h = HMAC.new(secret, digestmod=SHA256) >>> h.update(b'Hello') >>> print(h.hexdigest())
This is an example showing how to validate the MAC:
>>> from Crypto.Hash import HMAC, SHA256 >>> >>> # We have received a message 'msg' together >>> # with its MAC 'mac' >>> >>> secret = b'Swordfish' >>> h = HMAC.new(secret, digestmod=SHA256) >>> h.update(msg) >>> try: >>> h.hexverify(mac) >>> print("The message '%s' is authentic" % msg) >>> except ValueError: >>> print("The message or the key is wrong")
.. automodule:: Crypto.Hash.HMAC :members: