Skip to content

Latest commit

 

History

History
45 lines (35 loc) · 1.24 KB

hmac.rst

File metadata and controls

45 lines (35 loc) · 1.24 KB

HMAC

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")

Crypto.Hash.HMAC