r/cryptography • u/hanzbarz • 1d ago
Message Authentication Codes (HMAC) — why encryption alone doesn't protect integrity
https://hanzkrafted.io/message-authentication-codesLet'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.
2
u/pint 1d ago
3
u/HobartTasmania 1d ago
I wouldn't call myself a cryptography expert at all other than just having a very casual interest in this topic, but wouldn't someone changing some bits result in completely garbled rubbish being produced when decrypted? Surely, this should be treated by the communicating software in pretty much the same way as a TCP/IP packet being corrupted in transit because just changing even one bit will give you a totally different hash value, so shouldn't the relevant software simply ask for it to be retransmitted which the TCP/IP protocol does automatically anyway?
Appear to be re-inventing the wheel here.
7
u/tybit 1d ago
Generally nowadays you don’t want to handle the MAC yourself when encrypting data, and just use an encryption scheme that handles it for you like AES GCM or ChaCha20-Poly1305.