#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.
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 createt. A MAC suits two-party sessions (TLS, VPN, API), whereas third-party proof requires a digital signature.
- One shared secret key k
- Fast, ideal for TLS, VPN, API sessions
- No third-party non-repudiation
- 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.
- Normalize keyProduce block-sized key k'
- Inner hashinner = H((k' XOR ipad) || m)
- Outer hashtag = H((k' XOR opad) || inner)
- VerifyConstant-time tag comparison
In Python 3, use hmac with hmac.compare_digest:
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.
- Authenticates ciphertext C with key k2
- Rejects tampering before decryption
- Prevents padding-oracle attacks
- 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 (leakingP1 XOR P2) and lets an attacker recover the GHASH keyH(Joux's "forbidden attack") to forge tags for arbitrary messages. - Comparing tags with
==: Early-exit comparison leaks tag bytes via timing side channels. Always usehmac.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 withhmac.compare_digest.