Python Hmac Module
The hmac module implements the HMAC algorithm as described by RFC 2104. HMAC stands for Keyed-Hashing for Message Authentication.
Importing the Module
import hmac
Creating an HMAC Object
To create an HMAC object, you use the hmac.new() function. It requires a key and a message (optional at creation), and a digest module (default is usually MD5 in older versions, but it's best to specify, e.g., hashlib.sha256).
import hmac
import hashlib
key = b'secret-key'
msg = b'message-to-authenticate'
h = hmac.new(key, msg, hashlib.sha256)
Getting the Digest
digest()
Returns the digest of the bytes passed to the update() method so far.
print(h.digest())
hexdigest()
Returns the digest as a string of hexadecimal digits.
print(h.hexdigest())
Verifying Signatures
To prevent timing attacks, you should use hmac.compare_digest() instead of the == operator when verifying signatures.
import hmac
received_digest = "..." # The digest you received
calculated_digest = h.hexdigest()
if hmac.compare_digest(received_digest, calculated_digest):
print("Signature matches")
else:
print("Signature does not match")