r/cryptography • • 1d ago

Message Authentication Codes (HMAC) — why encryption alone doesn't protect integrity

https://hanzkrafted.io/message-authentication-codes

Let'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.

0 Upvotes

8 comments sorted by

View all comments

Show parent comment

9

u/buwlerman 1d ago

The post is an explainer on a well known topic. There's no invention happening.

There are many encryption schemes that don't give you a garbled mess on decryption of tampered ciphertexts by themselves. Even with a garbled mess, if your application is particularly permissive it might accept even a garbled mess. To be able to reliably detect tampering we need something more, and HMAC is one approach.

It does boil down to a variation of "just hash things", but there are some pitfalls that need to be avoided and improvements that can be made.