Skip to main content
Message Authentication Codes (HMAC) & Integrity
Lesson 4 of 5

Message Authentication Codes (HMAC) & Integrity

Learn why encryption alone does not prevent tampering, how HMAC and CMAC prove integrity and origin, and how modern AEAD ciphers protect data in transit.

Intermediate 22 min Cryptography

Learning objectives

  • Explain why unauthenticated encryption modes such as AES-CTR are vulnerable to bit-flipping malleability
  • Distinguish Message Authentication Codes from digital signatures and state the EUF-CMA security goal
  • Demonstrate why naive H(k || m) constructions fail to length extension and how HMAC and CMAC prevent forgery
  • Compare Encrypt-then-MAC with MAC-then-Encrypt and configure AEAD ciphers with Additional Authenticated Data
  • Prevent GCM nonce-reuse failures and timing side channels during tag verification in Python 3

Recommended first: Symmetric Encryption: AES, Block Modes & AEADCryptographic Hashing, Password KDFs & HMAC

#Why this matters

Symmetric encryption hides plaintext from passive eavesdroppers, but confidentiality alone cannot stop active tampering in transit. In AES-CTR mode, ciphertext is C = P XOR KS, where KS is the keystream. Because XOR is linear, flipping bits in a ciphertext byte flips the exact same bits in the decrypted plaintext byte.

If a payment service encrypts "100 dollars" with AES-CTR and no authentication tag, an attacker who knows the format can XOR the first ciphertext byte with ord('1') XOR ord('9'). The receiver decrypts "900 dollars" with no error. The attacker never learns the key, yet controls the plaintext. This flaw is called malleability, and preventing it requires message authentication.

#How MACs work and EUF-CMA security

A Message Authentication Code (MAC) computes a short tag t = MAC(k, m) from a shared secret key k and message m. The sender transmits (m, t). The receiver recomputes expected = MAC(k, m) and accepts m only if expected matches t.

Shared-key MAC generation and verificationShared-key MAC generation and verificationSenderReceiverm, t = MAC(k, m)Receiver recomputes expected = MAC(k, m)compare_digest(expected, t)Accept only on exact match

MAC security is defined by EUF-CMA (Existential Unforgeability under Chosen-Message Attack): even after seeing valid tags for chosen messages, an attacker cannot forge a valid tag for any new message. Keep three MAC boundaries in mind:

  • No confidentiality: A MAC tag does not encrypt m.
  • No replay protection: Valid (m, t) pairs can be replayed unless you include a sequence number, nonce, or timestamp.
  • No non-repudiation: Both parties share k, so either could create t. A MAC suits two-party sessions (TLS, VPN, API), whereas third-party proof requires a digital signature.
MAC vs Digital Signature
MAC (Symmetric)
  • One shared secret key k
  • Fast, ideal for TLS, VPN, API sessions
  • No third-party non-repudiation
Digital Signature (Asymmetric)
  • Private key sk and public key pk
  • Slower, supports public verification
  • Provides third-party non-repudiation

#Why H(k || m) fails and how HMAC and CMAC fix it

Prepending a secret key to a hash, t = H(k || m), fails on Merkle-Damgard hashes (such as SHA-256) due to a length extension attack. Because t exposes the hash's internal state after k || m, an attacker knowing t and the length of k can append data such as &admin=true (after the internal padding) and compute a valid tag without knowing k. Alternatives like H(m || k) and H(k || m || k) are also unreliable.

HMAC (RFC 2104) defeats length extension by nesting two keyed hashes using ipad = 0x36 and opad = 0x5C repeated to the block size:

HMAC(k, m) = H((k' XOR opad) || H((k' XOR ipad) || m))

Here k' is k normalized to one hash block. Hiding the inner digest inside an outer keyed hash stops length extension. HMAC-SHA256 powers TLS, IPsec, JWT (HS256), and TOTP. When a block cipher like AES is preferred over a hash, CMAC (NIST SP 800-38B) builds a secure MAC directly from AES.

  1. Normalize keyProduce block-sized key k'
  2. Inner hashinner = H((k' XOR ipad) || m)
  3. Outer hashtag = H((k' XOR opad) || inner)
  4. VerifyConstant-time tag comparison

In Python 3, use hmac with hmac.compare_digest:

python
import hashlib
import hmac

key = b"lab-shared-secret-key-32-bytes!!"
message = b"transfer=100&to=alice&seq=42"

tag = hmac.new(key, message, hashlib.sha256).digest()
print("Tag (hex):", tag.hex())

expected = hmac.new(key, message, hashlib.sha256).digest()
print("Valid:", hmac.compare_digest(expected, tag))

tampered = b"transfer=900&to=alice&seq=42"
expected_tampered = hmac.new(key, tampered, hashlib.sha256).digest()
print("Tampered valid:", hmac.compare_digest(expected_tampered, tag))

#Combining encryption with a MAC and modern AEAD

When combining symmetric encryption and a MAC manually, use only Encrypt-then-MAC (C = E(k1, m), t = MAC(k2, C)) with two separate keys. Because the receiver checks t over C before decrypting, tampered packets are rejected before touching padding logic. By contrast, MAC-then-Encrypt in TLS 1.2 and earlier enabled padding-oracle attacks (Vaudenay, Lucky Thirteen, POODLE) and was removed in TLS 1.3.

Encrypt-then-MAC vs MAC-then-Encrypt
Encrypt-then-MAC (Recommended)
  • Authenticates ciphertext C with key k2
  • Rejects tampering before decryption
  • Prevents padding-oracle attacks
MAC-then-Encrypt (Avoid)
  • Authenticates plaintext before encryption
  • Decrypts and unpads before checking tag
  • Enabled Lucky Thirteen and POODLE

Modern protocols replace manual composition with AEAD (Authenticated Encryption with Associated Data). An AEAD cipher provides confidentiality and authenticity in one primitive and also protects unencrypted Additional Authenticated Data (AAD) such as routing headers. The standard choices are AES-GCM (CTR plus GHASH) and ChaCha20-Poly1305 (RFC 8439); TLS 1.3 allows only AEAD.

#Defending / Common mistakes

  • GCM (key, nonce) reuse: Never repeat a nonce under one key in AES-GCM. Reuse cancels the CTR keystream (leaking P1 XOR P2) and lets an attacker recover the GHASH key H (Joux's "forbidden attack") to forge tags for arbitrary messages.
  • Comparing tags with ==: Early-exit comparison leaks tag bytes via timing side channels. Always use hmac.compare_digest.
  • Sharing one key for encryption and MAC: Derive separate keys (k1, k2) via a KDF such as HKDF.
  • Missing replay defense: Include sequence numbers or bounded timestamps in the authenticated data or AAD.

#Summary

  • Unauthenticated encryption (such as AES-CTR) is malleable and gives confidentiality without integrity.
  • A MAC proves integrity and origin under EUF-CMA for shared-key parties, without confidentiality or non-repudiation.
  • Naive H(k || m) fails to length extension; use HMAC (RFC 2104) or CMAC.
  • Prefer AEAD (AES-GCM, ChaCha20-Poly1305) with AAD, or Encrypt-then-MAC with two separate keys.
  • Never repeat a GCM (key, nonce) pair, and always verify tags in constant time with hmac.compare_digest.

Lecture presentations

Slides on this topic: view them in the browser or download the PDF.

Message authentication

MAC · HMAC and authenticated encryption

Slides: 24 PDF · 1007 KB

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge