Exercise 2: Why SHA256(key || message) Is an Unsafe MAC — Possible Solution ==================================================================== The naive construction SHA256(key || message) is vulnerable to a LENGTH-EXTENSION ATTACK, which the chapter names as the specific problem HMAC's nested structure exists to prevent. The conceptual issue: SHA-256 (like SHA-1, per Chapter 7) is built on the Merkle-Damgård construction, which processes input in fixed-size chunks and carries an internal "running state" forward from chunk to chunk. The FINAL output hash you normally see IS essentially a snapshot of that internal running state at the end of processing -- which means an attacker who knows only the hash output for key || message (without ever seeing the key itself) can, for certain hash constructions, resume computation from that exact state and compute a valid hash for key || message || extra_attacker_data -- effectively extending the original input and getting a correct hash for the extended version, without ever learning the key. Applied to this MAC construction: an attacker intercepting a valid (message, MAC) pair could potentially compute a NEW valid MAC for message || extra_data, appending their own chosen data to the original message, without ever needing to know the secret key at all -- defeating the entire point of using a keyed construction in the first place. What HMAC's nested double-hash structure prevents: HMAC's formula -- Hash((key XOR outerPad) || Hash((key XOR innerPad) || message)) -- computes an INNER hash first, then feeds that inner hash's OUTPUT (not the raw internal state) into a second, OUTER hash computation that also re-mixes in the key. Because the final output is the result of this second, outer hash operation -- not a direct snapshot of an internal state an attacker could resume from -- there is no equivalent "resume and extend" operation available to an attacker who only sees the final HMAC value. The key is folded in twice, at two different structural points, specifically to break the property that made the naive single-hash construction vulnerable. WHY THIS WORKS AS AN ANSWER ------------------------------ This directly explains the mechanism the chapter names but doesn't fully unpack -- "some hash constructions allow an attacker... to compute a valid hash... with extra data appended" -- by connecting it back to Chapter 7's own description of the Merkle-Damgård construction carrying state between chunks, and showing precisely how HMAC's nested structure (stated in the chapter's own formula) removes the specific property (a directly resumable internal state) that the naive construction exposed.