all Python 3hmacfunction
hmac.new()
message authentication
Creates an HMAC — a message signature with a secret key, letting a receiver with the same key check authenticity and integrity.
Syntax
h = hmac.new(key, msg=None, digestmod='sha256')
Unlike hashlib.sha256(key + msg), which falls to a length-extension attack, an HMAC cannot be forged without the key. digestmod has been required since 3.8 even though it is third: without it you get TypeError. Key and message are bytes, so encode a str first. Compare signatures with hmac.compare_digest(), not ==, or a timing attack becomes possible.
Examples
import hmac
sig = hmac.new(b'key', b'The quick brown fox jumps over the lazy dog', 'sha256')
print(sig.hexdigest()[:16]) # → f7bc83f430538424
hmac.new(b'key', b'msg') # → TypeError: Missing required argument 'digestmod'.
import hmac
key = b'server-secret'
expected = hmac.new(key, b'user=42', 'sha256').hexdigest()
received = hmac.new(key, b'user=42', 'sha256').hexdigest()
print(hmac.compare_digest(expected, received)) # → True
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy