Interface ReplayGuard

All Known Implementing Classes:
InMemoryReplayGuard

public interface ReplayGuard
Interface for preventing TOTP code replay attacks.

A replay attack occurs when an attacker intercepts a valid TOTP code and uses it again within its validity window. The ReplayGuard tracks used codes to prevent this.

Usage Pattern


 ReplayGuard guard = new InMemoryReplayGuard(Duration.ofMinutes(2));
 
 // During verification
 if (totp.verify(secret, code)) {
     String key = userId + ":" + code;
     if (guard.markUsed(key)) {
         // Code is valid and was not previously used
         authenticateUser();
     } else {
         // Code was already used - potential replay attack
         rejectAuthentication();
     }
 }
 

Implementation Notes

  • Keys should include user identifier to prevent cross-user attacks
  • Entries should expire after code validity window passes
  • Thread-safe implementation required for production use
See Also:
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    Clears all tracked codes.
    boolean
    Attempts to mark a code as used.
    int
    Returns the number of codes currently tracked.
    boolean
    Checks if a code has been used without marking it.
  • Method Details

    • markUsed

      boolean markUsed(String key)
      Attempts to mark a code as used.

      This method should be called after successful TOTP verification. Returns true only if the code was not previously used.

      Parameters:
      key - unique key combining user identifier and code
      Returns:
      true if the code was successfully marked as used (first use), false if the code was already used
    • wasUsed

      boolean wasUsed(String key)
      Checks if a code has been used without marking it.
      Parameters:
      key - the key to check
      Returns:
      true if the code was previously used
    • clear

      void clear()
      Clears all tracked codes.

      Use with caution - this resets replay protection.

    • size

      int size()
      Returns the number of codes currently tracked.
      Returns:
      count of tracked codes