A message authentication code (MAC) is an authentication tag computed from a message and a shared secret key. A receiver recomputes the tag with the same key: a match shows that someone without the key could not have replaced the message and tag together. A plain hash only detects accidental corruption, because an attacker can hash altered data themselves. section 7.1
Figure 7.3 MACs rely on a secret key that authenticates a message.
The shared secret is the crucial difference between an integrity digest and a MAC: both sender and receiver can calculate the tag, while an attacker cannot. section 7.1
MACs are symmetric: every verifier needs the secret and can therefore also forge valid tags. They authenticate messages between parties sharing that secret, but do not provide the asymmetric separation or nonrepudiation associated with digital signatures. section 7.1 section 9.1
Hash-based constructions differ sharply in failure modes:
- Secret-prefix MACs use MAC(key, message) = H(key || message). With Merkle–Damgård hashes such as MD5, SHA-1, and SHA-2, a known digest can enable a length-extension forgery. section 7.2 section 7.3
- Secret-suffix MACs use MAC(key, message) = H(message || key). They block length extension, but a collision in the underlying hash can make one tag validate two different messages. section 7.2 section 7.4
- HMAC applies the hash twice and is recommended for message authenticity because it resists both length-extension and collision attacks described here. section 7.2 section 7.6
Forging a bank transaction
A bank API sorts request parameters, concatenates them after a client secret, and hashes the result with SHA-256. An attacker who captures a valid transaction MAC can reconstruct the hash state from its digest, account for padding, append a new amount and timestamp, and submit a forged request without learning the secret. The exploit succeeds because the server’s parameter encoding lets the padded original input and malicious fields produce the extended hash input. section 7.3.1 section 7.3.2
Do not invent a MAC by concatenating a secret with a hash input. Prefer HMAC for authenticity; when confidentiality is also needed, use authenticated encryption rather than composing encryption and MAC operations yourself. section 7.6 section 10.8.3



