all Python 3hmacterm
hmac
module
Signing a message with a secret key using HMAC: checking that data came from the key holder and was not altered.
Syntax
import hmac
Use hmac for signing: webhooks, tokens, signed links. A plain hash from hashlib does not work here, since anyone can compute it, while an HMAC cannot be forged without the key. Signatures are compared with hmac.compare_digest, not ==: an ordinary comparison leaks through its running time how many leading characters matched.
Examples
import hmac, hashlib
key = b'secret'
sig = hmac.new(key, b'message', hashlib.sha256).hexdigest()
print(len(sig)) # → 64
check = hmac.new(key, b'message', 'sha256').hexdigest()
print(hmac.compare_digest(sig, check)) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy