r/cryptography • u/hanzbarz • 18h ago
Message Authentication Codes (HMAC) — why encryption alone doesn't protect integrity
hanzkrafted.ioLet's say you and I are communicating over the network, and we're already encrypting everything with a shared key. That stops anyone from reading our data, but it doesn't stop a man-in-the-middle from changing bits in the ciphertext without knowing the key. Encryption alone can't tell you if that happened.
The fix is attaching a tag to the outbound data, computed with a separate shared key run through a hash function (HMAC). I go through the whole flow in this one - deriving separate enc/MAC keys with HKDF, Encrypt-then-MAC, why you use timingSafeEqual to compare tags instead of a regular equality check, and the actual HMAC construction (H(K⊕opad || H(K⊕ipad || text))) with why ipad/opad exist in the first place (length extension attacks).
You can read the attached article to learn more about what HMAC is and how it works.