On this page
hmac
Prev: heapq | Up: stdlib_module | Next: html
Rel: hashlib, secrets
Ref: docs.python.org — hmac
Tags: #public #python3 #stdlib
Import
import hmac
Overview
Keyed-Hash Message Authentication Code (RFC 2104) combining a secret key with a cryptographic hash from hashlib (such as SHA-256) to verify both message integrity and authenticity. Essential for signing and verifying webhook payloads, API requests, and tamper-evident tokens.
Quick Start
import hmac
secret = b"shared-webhook-secret"
body = b'{"event":"release","tag":"v0.1.0"}'
sig = hmac.digest(secret, body, "sha256").hex()
expected = hmac.digest(secret, body, "sha256").hex()
assert hmac.compare_digest(sig, expected)
Implementation Walkthrough
1. Verifying an Incoming Webhook Signature Safely
import hashlib
import hmac
def sign_payload(secret: bytes, payload: bytes) -> str:
return "sha256=" + hmac.new(secret, payload, hashlib.sha256).hexdigest()
def verify_payload(secret: bytes, payload: bytes, header_sig: str) -> bool:
expected = sign_payload(secret, payload)
return hmac.compare_digest(expected.encode("ascii"), header_sig.encode("ascii"))
key = b"top-secret"
msg = b"hello"
hdr = sign_payload(key, msg)
assert verify_payload(key, msg, hdr)
assert not verify_payload(key, b"tampered", hdr)
2. Streaming Large Payloads Incrementally
import hashlib
import hmac
mac = hmac.new(b"secret", digestmod=hashlib.sha256)
for chunk in (b"part-1-", b"part-2"):
mac.update(chunk)
tag = mac.hexdigest()
Gotchas & Boundaries
- Always verify signatures with
hmac.compare_digest(): Never use==, which short-circuits on the first mismatching byte and leaks timing information. - Always specify
digestmodexplicitly: Pass"sha256"orhashlib.sha256(avoidmd5orsha1). - HMAC authenticates integrity, not confidentiality: The message body remains plaintext; encrypt separately if confidentiality is needed.
- Sign the exact raw request bytes, not a re-serialized JSON dict whose whitespace or key order may differ.
Common Functions
- hmac.compare_digest() —
compare_digest(a, b, /)— Return 'a == b'. - hmac.digest() —
digest(key, msg, digest)— Fast inline implementation of HMAC. - hmac.new() —
new(key, msg=None, digestmod='')— Create a new hashing object and return it.
Classes & Objects
- hmac.HMAC — RFC 2104 HMAC class. Also complies with RFC 4231. (Methods:
.copy(),.digest(),.hexdigest(),.name(),.update())
Constants & Attributes
hmac.digest_size(NoneType) =Nonehmac.trans_36(bytes) =b'67452301>?<=:;89&\'$%"# !./,-*+()\x16\x17\x14\x15\x12\x...hmac.trans_5C(bytes) =b'\\]^_XYZ[TUVWPQRSLMNOHIJKDEFG@ABC|}~\x7fxyz{tuvwpqrslmn...
Linked from
Related notes
- tuts/python3/stdlib_module/hashlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/heapq Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/html Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/secrets Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/hmac/compare_digest Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/hmac/digest Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/hmac/HMAC Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/hmac/new Linked here; shared tags: #stdlib