Python hmac - keyed hashing and compare_digest
Answer: hmac.new returns a new hmac object. The module implements the HMAC algorithm as a keyed hash. Use compare_digest to return a == b for two digest values.
Examples
import hmac, hashlib, os
key = os.urandom(32)
sig = hmac.new(key, b"payload", hashlib.sha256).hexdigest()
def ok(given: str) -> bool:
expected = hmac.new(key, b"payload", hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, given)
Rules
- Pass a
digestmodsuch as"sha256"when you create the object. digest()returns bytes;hexdigest()returns a hex string.
See also
Claims
- id: C1 claim: new returns a new hmac object. source: S1 evidence: "Return a new hmac object"
- id: C2 claim: compare_digest compares values as a == b. source: S1 evidence: "Return a == b"
- id: C3 claim: The module implements the HMAC algorithm. source: S2 evidence: "Implements the HMAC algorithm"
Sources
- [S1] hmac - Keyed-hashing for message authentication. Python docs. https://docs.python.org/3/library/hmac.html . License: PSF-2.0. Accessed 2026-11-18.
- [S2] Lib/hmac.py. python/cpython (GitHub). https://github.com/python/cpython/blob/main/Lib/hmac.py . License: PSF-2.0. Accessed 2026-11-18.
License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, hmac - Keyed-hashing for message authentication; python/cpython (GitHub), Lib/hmac.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.
License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, hmac - Keyed-hashing for message authentication; python/cpython (GitHub), Lib/hmac.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.
Cite this
iinventedlight. 2026. "Python hmac - keyed hashing and compare_digest." iinventedlight Library, iil:note:nhgne2z0, version of 2026-11-18. https://iinventedlight.com/library/notes/python-hmac/. License: CC-BY-4.0.
@misc{iil_note_nhgne2z0,
author = {{iinventedlight}},
title = {{Python hmac - keyed hashing and compare\_digest}},
howpublished = {iinventedlight Library},
year = {2026},
date = {2026-11-18},
url = {https://iinventedlight.com/library/notes/python-hmac/},
note = {Permanent ID iil:note:nhgne2z0. License: CC-BY-4.0.},
}
Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).
For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-hmac.md.