How does the secret key in an HMAC prevent modification of the HMAC? Just as a preface: I'm not implementing a HMAC - I just want to understand it, as it is part of of my Computer Science course.

When using Hash-based message authentication codes, I understand that you need to protect the front and back of the MAC to prevent an adversary from modifying the HMAC while in transit.

HMAC (K,m) = H((K ⊕ opad) ∥ H((K ⊕ ipad) ∥ m))


As such, a HMAC is constructed by hashing the XOR of the secret key K with the outer padding opad concatentated with the hash of the secret key K XORed with the inner padding ipad concatenated with the message.

Can someone explain how these “secret keys XORed with padding” protect the HMAC from modification by an adversary (such as appending data to the end of the MAC)?
To attack a MAC in general, the attacker needs to find a valid MAC of a message that they do not have the MAC for (or find a message collision that allows a different message to have the same MAC digest). In this case, the attacker would be appending data to the original message, not the MAC itself, and trying to obtain a valid MAC for the new message. In specific, it sounds like you are thinking of length-extension attacks.

In HMAC, the inner hash by itself would be vulnerable to a length-extension attack and the attacker could successfully calculate a valid inner hash digest without access to the key. However, the outer hash isn't vulnerable to a length-extension attack since the client performing the HMAC authentication is only going to input the fixed length string key || inner_hash into it. The attacker only controls variable-length input to the inner hash, not the outer hash.

This is more-or-less addressed by this answer to another question. Relevant excerpt:


  the role of the inner function is to provide collision-resistance (to compress a long message down to a short fingerprint, in a way so that someone who does not know the key cannot find a pair of messages with the same fingerprint), and the role of the outer function is to act as a message authentication code on this fingerprint.