← All notes

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

See also

Claims

Sources

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

Permanent ID: iil:note:nhgne2z0

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.},
}

Markdown

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.