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.
HMAC(key, algorithm, backend=None)¶
HMAC objects take a
keyshould be randomly generated bytes and is recommended to be equal in length to the
digest_sizeof the hash function chosen. You must keep the
This is an implementation of RFC 2104.
>>> from cryptography.hazmat.primitives import hashes, hmac >>> h = hmac.HMAC(key, hashes.SHA256()) >>> h.update(b"message to hash") >>> h.finalize() b'#F\xdaI\x8b"e\xc4\xf1\xbb\x9a\x8fc\xff\xf5\xdex.\xbc\xcd/+\x8a\x86\x1d\x84\'\xc3\xa6\x1d\xd8J'
If the backend doesn’t support the requested
UnsupportedAlgorithmexception will be raised.
TypeErrorwill 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.verify(b"an incorrect signature") Traceback (most recent call last): ... cryptography.exceptions.InvalidSignature: Signature did not match digest.
msg (bytes-like) – The bytes to hash and authenticate.
Returns: A new instance of
HMACthat can be updated and finalized independently of the original instance.
Raises: cryptography.exceptions.AlreadyFinalized – See
Finalize the current context and securely compare digest to
signature (bytes) – The bytes to compare the current digest against.
Finalize the current context and return the message digest as bytes.
Return bytes: The message digest as bytes. Raises: cryptography.exceptions.AlreadyFinalized –