This is a “Hazardous Materials” module. You should ONLY use it if you’re 100% absolutely sure that you know what you’re doing because this module is full of land mines, dragons, and dinosaurs with laser guns.

Hash-based message authentication codes (HMAC)

Hash-based message authentication codes (or HMACs) are a tool for calculating message authentication codes using a cryptographic hash function coupled with a secret key. You can use an HMAC to verify both the integrity and authenticity of a message.

class cryptography.hazmat.primitives.hmac.HMAC(key, algorithm)

HMAC objects take a key and a HashAlgorithm instance. The key should be randomly generated bytes and is recommended to be equal in length to the digest_size of the hash function chosen. You must keep the key secret.

This is an implementation of RFC 2104.

>>> from cryptography.hazmat.primitives import hashes, hmac
>>> key = b'test key. Beware! A real key should use os.urandom or TRNG to generate'
>>> h = hmac.HMAC(key, hashes.SHA256())
>>> h.update(b"message to hash")
>>> signature = h.finalize()
>>> signature

If algorithm isn’t a HashAlgorithm instance then TypeError will be raised.

To check that a given signature is correct use the verify() method. You will receive an exception if the signature is wrong:

>>> h = hmac.HMAC(key, hashes.SHA256())
>>> h.update(b"message to hash")
>>> h_copy = h.copy() # get a copy of `h' to be reused
>>> h.verify(signature)
>>> h_copy.verify(b"an incorrect signature")
Traceback (most recent call last):
cryptography.exceptions.InvalidSignature: Signature did not match digest.

cryptography.exceptions.UnsupportedAlgorithm – This is raised if the provided algorithm isn’t supported.


msg (bytes-like) – The bytes to hash and authenticate.


Copy this HMAC instance, usually so that we may call finalize() to get an intermediate digest value while we continue to call update() on the original instance.


A new instance of HMAC that can be updated and finalized independently of the original instance.


cryptography.exceptions.AlreadyFinalized – See finalize()


Finalize the current context and securely compare digest to signature.


signature (bytes) – The bytes to compare the current digest against.


Finalize the current context and return the message digest as bytes.

After finalize has been called this object can no longer be used and update(), copy(), verify() and finalize() will raise an AlreadyFinalized exception.

Return bytes:

The message digest as bytes.