This question already has an answer here:

I read about HMAC and want to be sure if it protects against replay attacks as well.


marked as duplicate by e-sushi Jan 11 '18 at 5:43

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


No, a MAC only prevents an attacker from modifying the message. On its own, it does nothing to stop the attacker from resending a valid message unchanged.

To stop such replay attacks, your message have to include some contextual information that will make an originally valid message invalid if replayed. For example, if your messages each have a sequential message number, you could simply reject any messages with the same or lower number than the highest-numbered valid message you've received so far.

(Of course, you also should be prepared to deal with the possibility that legitimate messages may be lost or arrive out of order, either due to active attacks or simply due to unreliable communications. One option could be to use a non-cryptographic transport layer such as TCP to take care of message ordering and retransmission, and only use crypto on the application layer to verify that the data stream received over TCP has not been tampered with. Another option would be to implement your own message transport protocol, e.g. using a sliding window approach to deal with accidental message reordering.)

What a MAC (computed over the entire message, including metadata) can do is protect these message numbers (and other relevant metadata) from tampering, so that an attacker can't simply change the message number on their replayed messages, or e.g. copy the message number from one valid message to another.

  • $\begingroup$ What about nonces? I read that with HMAC with nonces could. Does it not help against replay attacks? $\endgroup$ – bruno fagioli Jan 11 '18 at 12:42
  • $\begingroup$ Yes, nonces can prevent replay attacks, if the recipient checks that they're never repeated. A lot of encryption systems need nonces for other reasons anyway, so you can use the same nonces for both purposes if you want. The sequential message numbers I mentioned above could be used as nonces, for example. And a MAC can then help ensure that an attacker can't tamper with the nonces. $\endgroup$ – Ilmari Karonen Jan 11 '18 at 15:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.