HMAC & Message Authentication
A plain hash proves that data matches a digest, but anyone can compute a new digest for modified data. To prove that a message was produced by someone who knows a secret key, you need a message authentication code (MAC). The standard construction is HMAC: a hash function (usually SHA-256) mixed with a key in a specific, well-analysed way.
| Hash | HMAC | Digital signature | |
|---|---|---|---|
| Needs a secret? | No | Yes, a shared key | Yes, a private key |
| Who can create it? | Anyone | Anyone with the key | Only the private key holder |
| Who can verify it? | Anyone | Anyone with the same key | Anyone with the public key |
| Proves | Integrity (against accidents) | Integrity + authenticity between key holders | Integrity + authenticity + non-repudiation |
Computing an HMAC
import hmac
import hashlib
key = b"demo-shared-secret-key-32-bytes!" # DEMO ONLY: use secrets.token_bytes(32)
message = b'{"user": "alice", "amount": 25}'
tag = hmac.new(key, message, hashlib.sha256).hexdigest()
print("tag:", tag)
# Changing one byte of the message or using another key changes the tag
print(hmac.new(key, message.replace(b"25", b"95"), hashlib.sha256).hexdigest()[:16])
print(hmac.new(b"another key", message, hashlib.sha256).hexdigest()[:16])tag: a0d7a4b1c333c27e397ff9987b073c83ed851e4f5189f40f496639b7cf889c54
91354a12765c7288
ee97b0d06544a143
The receiver, who knows the same key, recomputes the tag over the message it received and compares. An attacker who changes the amount cannot produce a matching tag without the key.
Verify in constant time
Comparing tags with == stops at the first different character, so the comparison takes slightly longer the more leading characters match. Over many attempts, that timing side channel can leak a valid tag character by character. Always compare MACs with hmac.compare_digest, which takes the same time regardless of where the difference is:
import hmac
import hashlib
KEY = b"demo-shared-secret-key-32-bytes!"
def sign(message: bytes) -> str:
return hmac.new(KEY, message, hashlib.sha256).hexdigest()
def verify(message: bytes, tag: str) -> bool:
return hmac.compare_digest(sign(message), tag)
msg = b"order=1042&status=paid"
tag = sign(msg)
print(verify(msg, tag))
print(verify(b"order=1042&status=refunded", tag))
print(verify(msg, "0" * 64))True
False
False
Real-world use: webhook signatures
Payment providers and code-hosting services send webhooks (HTTP callbacks) to your server. To let you check that a webhook really came from them, they sign the body with a shared secret and put the HMAC in a header. A good verifier also includes a timestamp in the signed data and rejects old messages, so a captured request can't be replayed later:
import hmac
import hashlib
SECRET = b"whsec_demo_only_secret"
TOLERANCE = 300 # seconds
def make_signature(timestamp: int, body: bytes) -> str:
signed = str(timestamp).encode() + b"." + body
return hmac.new(SECRET, signed, hashlib.sha256).hexdigest()
def check_webhook(headers, body, now):
ts = int(headers["X-Timestamp"])
if abs(now - ts) > TOLERANCE:
return "rejected: too old (possible replay)"
expected = make_signature(ts, body)
if not hmac.compare_digest(expected, headers["X-Signature"]):
return "rejected: bad signature"
return "accepted"
body = b'{"event": "invoice.paid", "id": "in_778"}'
sent_at = 1767225600 # fixed time for the demo
good = {"X-Timestamp": str(sent_at), "X-Signature": make_signature(sent_at, body)}
print(check_webhook(good, body, now=sent_at + 4))
print(check_webhook(good, body.replace(b"paid", b"void"), now=sent_at + 4))
print(check_webhook(good, body, now=sent_at + 3600))accepted
rejected: bad signature
rejected: too old (possible replay)
Three checks, three different outcomes: genuine, tampered, and replayed an hour later.
Why not just hash(key + message)?
It is tempting to build a MAC as sha256(key + message). With SHA-256 that is vulnerable to a length-extension attack: from a valid tag, someone without the key can compute a valid tag for the message with extra data appended. HMAC's nested construction (H(key ⊕ opad, H(key ⊕ ipad, message))) was designed to prevent this. Use the library's HMAC rather than inventing a construction.
import hmac
import hashlib
key = b"k" * 32
msg = b"amount=10"
# hmac.new does the inner/outer padding for you; this is the same computation by hand
block = 64 # SHA-256 block size in bytes
k = key.ljust(block, b"\x00")
inner = hashlib.sha256(bytes(b ^ 0x36 for b in k) + msg).digest()
outer = hashlib.sha256(bytes(b ^ 0x5C for b in k) + inner).hexdigest()
print(outer == hmac.new(key, msg, hashlib.sha256).hexdigest())True
You will never need to write this yourself, but it shows HMAC is just two hashes with the key mixed in differently each time.
Key handling
- Generate MAC keys with a secure random source (
secrets.token_bytes(32)), never a word or a project name. - Keep keys out of source code (see the Secure Coding lesson) and rotate them if they may have leaked.
- Use different keys for different purposes (session cookies vs. webhooks), so a leak of one doesn't compromise the other.
Go further: HMAC and Timing-Safe Comparison builds HMAC from its two passes, and Length Extension forges a
hash(secret || message)tag on a toy API.
Test yourself
What does an HMAC prove that a plain SHA-256 hash doesn't?
- That the data is encrypted
- That the data was produced by someone holding the secret key
- That the data is small
- That nobody else saw the data
Why use hmac.compare_digest instead of == to compare tags?
- It is faster
- It runs in constant time, preventing timing attacks
- It accepts hex and bytes
- == doesn't work for strings
Why does a webhook verifier include a timestamp in the signed data?
- To sort events
- To reject replays of old, captured requests
- To make the HMAC longer
- Timestamps are required by HTTP