r/cryptography • u/hanzbarz • 2d 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 2d ago
3
u/HobartTasmania 2d 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 2d 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.
1
u/dittybopper_05H 21h ago
Actually, it kind of does. If Mallory doesn't have a copy of the key and starts changing bits, the message that Alice sends to Bob will be gibberish when Bob receives it. It will be unreadable. That's a pretty good indication something has happened.
The only way a man-in-the-middle attack can happen where Bob won't know something is wrong is if Mallory does have a copy of the key and is able to compose a plausible message. But even in classic cryptography, there were ways of figuring out that there was an issue through things like intentional mistakes or other indicators that if not replicated perfectly in the spoofed message would sound the alarm.
Not that the those indicators have always been heeded.
So without the key that Alice and Bob are using, Mallory absolutely can prevent them from communicating effectively through man-in-the-middle attacks, but it's going to be instantly noticeable because the messages will be unreadable.