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")
- class Crypto.Hash.HMAC.HMAC(key, msg=b'', digestmod=None)¶
An HMAC hash object. Do not instantiate directly. Use the
digest_size (integer) – the size in bytes of the resulting MAC tag
Return a copy (“clone”) of the HMAC object.
The copy will have the same internal state as the original HMAC object. This can be used to efficiently compute the MAC tag of byte strings that share a common initial substring.
Return the binary (non-printable) MAC tag of the message authenticated so far.
The MAC tag digest, computed over the data processed so far. Binary form.
- Return type:
Return the printable MAC tag of the message authenticated so far.
The MAC tag, computed over the data processed so far. Hexadecimal encoded.
- Return type:
Verify that a given printable MAC (computed by another party) is valid.
hex_mac_tag (string) – the expected MAC of the message, as a hexadecimal string.
ValueError – if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect.
Authenticate the next chunk of message.
data (byte string/byte array/memoryview) – The next chunk of data
Verify that a given binary MAC (computed by another party) is valid.
mac_tag (byte string/byte string/memoryview) – the expected MAC of the message.
- Crypto.Hash.HMAC.new(key, msg=b'', digestmod=None)¶
Create a new MAC object.
key (bytes/bytearray/memoryview) – key for the MAC object. It must be long enough to match the expected security level of the MAC.
msg (bytes/bytearray/memoryview) – Optional. The very first chunk of the message to authenticate. It is equivalent to an early call to
digestmod (module) – The hash to use to implement the HMAC. Default is