MACs & Authenticated Encryption
Protecting integrity and authenticity — message authentication codes, HMAC, Poly1305, constant-time verification, encrypt-then-MAC vs the alternatives, AEAD (AES-GCM, ChaCha20-Poly1305), associated data, and real uses like signed cookies, webhooks and API request signing.
Encryption hides content but doesn't stop tampering: in CTR mode, flipping a ciphertext bit flips the same plaintext bit (Block cipher modes). And sometimes you don't need secrecy at all, only proof that a message is genuine and unmodified — a session cookie, a webhook, an API request. That's the job of a message authentication code (MAC).
MACs
A MAC is a short tag computed from a message and a secret key:
The receiver, who shares K, recomputes the tag and compares. Without K, an attacker can't produce a valid tag for any new or modified message — even after seeing many valid (message, tag) pairs.
| Hash | MAC | Digital signature | |
|---|---|---|---|
| Key | None | Shared secret | Private key signs, public key verifies |
| Who can create | Anyone | Anyone with the key | Only the private-key holder |
| Who can verify | Anyone | Only key holders | Anyone |
| Non-repudiation | — | No (both sides could have made it) | Yes |
| Speed | Fast | Fast | Slower |
HMAC
The standard MAC built from a hash function (Hash functions):
The nested construction defeats length-extension attacks that break the naive H(key ∥ message). HMAC-SHA256 is ubiquitous: JWTs with HS256, AWS request signing (SigV4), webhook signatures, TOTP codes, TLS 1.2 key derivation.
import hmac, hashlib
key = b"server-secret-from-kms"
msg = b'{"order_id": 42, "amount": 4999}'
tag = hmac.new(key, msg, hashlib.sha256).hexdigest()
def verify(msg: bytes, received_tag: str) -> bool:
expected = hmac.new(key, msg, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, received_tag) # constant-time comparison!Constant-time comparison
A normal == returns as soon as the first byte differs. By timing responses, an attacker can guess a valid tag one byte at a time — turning 2²⁵⁶ work into a few thousand requests. Always compare MACs with a constant-time function: hmac.compare_digest (Python), crypto.timingSafeEqual (Node), MessageDigest.isEqual (Java), subtle.ConstantTimeCompare (Go).
Other MACs
- Poly1305: a very fast one-time MAC, paired with ChaCha20 (each message gets a fresh Poly1305 key derived from the stream cipher).
- GMAC/GHASH: the authenticator inside AES-GCM.
- CMAC: built from a block cipher; used in banking and embedded systems.
- KMAC/BLAKE3 keyed mode: modern hash-based alternatives without HMAC's nesting.
Combining encryption and MACs
Three ways to combine a cipher and a MAC:
| Order | Construction | Security |
|---|---|---|
| Encrypt-then-MAC | Encrypt, then MAC the ciphertext | Secure — verify before decrypting; tampered ciphertext is rejected without touching the decryption code |
| MAC-then-encrypt | MAC the plaintext, then encrypt both | Fragile — enabled padding oracle attacks in TLS (Lucky Thirteen) |
| Encrypt-and-MAC | Encrypt and separately MAC the plaintext | Can leak information (the MAC of identical plaintexts is identical) |
Even encrypt-then-MAC needs care: separate keys for encryption and MAC, and the MAC must cover the IV and any metadata. Rather than assembling it yourself, use an AEAD.
AEAD: authenticated encryption with associated data
An AEAD scheme provides confidentiality + integrity + authenticity in one primitive with a simple interface:
seal(key, nonce, plaintext, associated_data) → ciphertext ‖ tag
open(key, nonce, ciphertext ‖ tag, associated_data) → plaintext or ERROR| AEAD | Notes |
|---|---|
| AES-GCM | The standard; hardware-accelerated; 96-bit nonce must never repeat |
| ChaCha20-Poly1305 | Fast everywhere, constant-time; TLS, WireGuard, SSH |
| XChaCha20-Poly1305 | 192-bit nonce — safe to generate randomly |
| AES-GCM-SIV | Nonce-misuse-resistant: a repeated nonce only reveals whether two messages were identical |
| AES-CCM, AES-OCB | Constrained devices / patent-free since 2021 respectively |
Associated data is authenticated but not encrypted: packet headers, a database row ID, a user ID, a schema version. Binding it prevents cut-and-paste attacks — e.g. moving user A's encrypted SSN into user B's row would fail authentication because the row ID differs.
// Web Crypto API (browsers and Node)
const key = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
const iv = crypto.getRandomValues(new Uint8Array(12));
const ct = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv, additionalData: new TextEncoder().encode("user:42") },
key, new TextEncoder().encode("4111 1111 1111 1111"));
// decrypt with the same iv and additionalData; throws on any tamperingIf decryption fails, return a single generic error and release no partial plaintext.
Real-world uses
Signed cookies and tokens
Store state on the client, protected from tampering: value.HMAC(value). The server verifies the tag on each request. Frameworks do this for session cookies (Flask, Rails, Express cookie-signature). JWTs signed with HS256 are the same idea (Authentication). Remember: signed ≠ encrypted — the client can read the value; use an AEAD if it must be secret.
Webhook signatures
Services like Stripe and GitHub sign webhook bodies so you can verify they're genuine:
def verify_webhook(raw_body: bytes, header_sig: str, timestamp: str, secret: bytes) -> bool:
if abs(time.time() - int(timestamp)) > 300: # reject stale requests (replay)
return False
signed = timestamp.encode() + b"." + raw_body # MAC the exact raw bytes
expected = hmac.new(secret, signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, header_sig)Verify against the raw body (re-serialised JSON may differ), include a timestamp to prevent replay, and compare in constant time.
API request signing
AWS SigV4 signs the method, path, query, selected headers, body hash and timestamp with a key derived from the secret access key — so a request can't be modified or replayed later, and the secret never travels over the network.
Replay protection
A valid MAC proves a message is authentic — not that it's fresh. An attacker can resend a captured message ("transfer ₹500") later. Include a timestamp, a nonce the server remembers, or a sequence number, and cover it with the MAC.
- A MAC proves integrity and authenticity using a shared key; it doesn't provide non-repudiation.
- HMAC-SHA256 is the standard MAC; never use H(key ∥ message).
- Always verify MACs with constant-time comparison.
- Encrypt-then-MAC is the safe composition, but prefer an AEAD (AES-GCM, ChaCha20-Poly1305).
- Associated data binds context (IDs, headers) to ciphertext to prevent cut-and-paste attacks.
- Signed cookies, webhooks and API signatures are MACs in practice — add timestamps or nonces against replay.