Class DefaultCodeVerifier

java.lang.Object
com.iizix.totp.DefaultCodeVerifier

public class DefaultCodeVerifier extends Object
Verifies a code against a shared secret for the current time period and the allowed discrepancy either side of it (RFC 6238 section 5.2). Defaults: period 30 seconds, discrepancy 1, i.e. a 90 second acceptance window.
  • Field Details

  • Constructor Details

    • DefaultCodeVerifier

      public DefaultCodeVerifier(CodeGenerator codeGenerator, TimeProvider timeProvider)
      Constructs a verifier.
      Parameters:
      codeGenerator - The code generator, configured with the same algorithm and digits as the authenticator app.
      timeProvider - The time source.
      Throws:
      NullPointerException - If either parameter is null.
  • Method Details

    • setTimePeriod

      public void setTimePeriod(int timePeriod)
      Sets the time period in seconds, default 30. Must equal the period the authenticator app was enrolled with.
      Parameters:
      timePeriod - The period in seconds, at least 1.
      Throws:
      IllegalArgumentException - If timePeriod is less than 1.
    • setAllowedTimePeriodDiscrepancy

      public void setAllowedTimePeriodDiscrepancy(int allowedTimePeriodDiscrepancy)
      Sets the number of time periods either side of the current one for which a code is still accepted, default 1. The acceptance window is (2*discrepancy+1)*timePeriod seconds.
      Parameters:
      allowedTimePeriodDiscrepancy - The discrepancy, zero or more.
      Throws:
      IllegalArgumentException - If allowedTimePeriodDiscrepancy is negative.
    • isValidCode

      public boolean isValidCode(String secret, String code)
      Verifies a code. A null secret or code is never valid.
      Parameters:
      secret - The Base32 shared secret.
      code - The code entered by the user.
      Returns:
      true if the code is the one for the current time period or for a period within the allowed discrepancy, false otherwise.
    • getValidTimeStep

      public long getValidTimeStep(String secret, String code)
      Verifies a code and tells which time step it is the code of. A caller needs the step to refuse a code that was accepted before (RFC 6238 section 5.2: the verifier must not accept the second attempt of a code after the first was validated): it keeps the step of the last code it accepted and refuses every code whose step is not later than that.

      Every candidate step is computed and compared, even after a match, to avoid timing attacks. A null secret or code matches no step.

      Parameters:
      secret - The Base32 shared secret.
      code - The code entered by the user.
      Returns:
      The time step the code is the code of - the count of time periods since the epoch, the current one or one within the allowed discrepancy, the latest of them when more than one matches - or NO_STEP when the code is not valid.