Package Cryptodome :: Package Hash :: Module HMAC

Module HMAC

HMAC (Hash-based Message Authentication Code) algorithm

HMAC is a MAC defined in RFC2104 and FIPS-198 and constructed using a cryptograpic hash algorithm. It is usually named HMAC-X, where X is the hash algorithm; for instance HMAC-SHA1 or HMAC-MD5.

The strength of an HMAC depends on:

This is an example showing how to create a MAC:

>>> from Cryptodome.Hash import HMAC
>>>
>>> secret = b'Swordfish'
>>> h = HMAC.new(secret)
>>> h.update(b'Hello')
>>> print h.hexdigest()

This is an example showing how to check a MAC:

>>> from Cryptodome.Hash import HMAC
>>>
>>> # We have received a message 'msg' together
>>> # with its MAC 'mac'
>>>
>>> secret = b'Swordfish'
>>> h = HMAC.new(secret)
>>> h.update(msg)
>>> try:
>>>   h.verify(mac)
>>>   print "The message '%s' is authentic" % msg
>>> except ValueError:
>>>   print "The message or the key is wrong"
Classes
  HMAC
Class that implements HMAC
Functions
 
new(key, msg='', digestmod=None)
Create a new HMAC object.
Function Details

new(key, msg='', digestmod=None)

 
Create a new HMAC object.
Parameters:
  • key (byte string) - key for the MAC object. It must be long enough to match the expected security level of the MAC. However, there is no benefit in using keys longer than the digest_size of the underlying hash algorithm.
  • msg (byte string) - The very first chunk of the message to authenticate. It is equivalent to an early call to HMAC.update(). Optional.
  • digestmod (A hash module or instantiated object from Cryptodome.Hash) - The hash to use to implement the HMAC. Default is Cryptodome.Hash.MD5.
Returns:
An HMAC object