Class TOTPClock

java.lang.Object
io.github.pratiyush.totp.internal.TOTPClock

public final class TOTPClock extends Object
Provides time for TOTP calculations with support for testing.

In production, use systemUTC() which delegates to the system clock. For testing, use fixed(Instant) to control the time.

Usage Examples


 // Production
 TOTPClock clock = TOTPClock.systemUTC();
 long counter = clock.getCurrentCounter(30);
 
 // Testing
 Instant testTime = Instant.parse("2009-02-13T23:31:30Z");
 TOTPClock clock = TOTPClock.fixed(testTime);
 
  • Method Details

    • systemUTC

      public static TOTPClock systemUTC()
      Creates a clock using the system UTC time.
      Returns:
      system UTC clock
    • fixed

      public static TOTPClock fixed(Instant instant)
      Creates a clock fixed at the specified instant.

      Useful for testing with specific timestamps.

      Parameters:
      instant - the fixed time
      Returns:
      fixed clock
    • of

      public static TOTPClock of(Clock clock)
      Creates a clock from a Java Clock instance.
      Parameters:
      clock - the clock to use
      Returns:
      TOTP clock wrapper
    • now

      public Instant now()
      Returns the current time as an Instant.
      Returns:
      current time
    • currentTimeSeconds

      public long currentTimeSeconds()
      Returns the current Unix timestamp in seconds.
      Returns:
      seconds since Unix epoch
    • getCurrentCounter

      public long getCurrentCounter(int periodSeconds)
      Returns the current TOTP counter value.

      The counter is calculated as: floor(currentTime / periodSeconds)

      Parameters:
      periodSeconds - the TOTP period in seconds
      Returns:
      current counter value
    • getCounterForInstant

      public static long getCounterForInstant(Instant instant, int periodSeconds)
      Returns the counter value for a specific timestamp.
      Parameters:
      instant - the timestamp
      periodSeconds - the TOTP period in seconds
      Returns:
      counter value for that timestamp
    • getSecondsRemaining

      public int getSecondsRemaining(int periodSeconds)
      Returns the number of seconds remaining in the current period.
      Parameters:
      periodSeconds - the TOTP period in seconds
      Returns:
      seconds until the current code expires
    • getJavaClock

      public Clock getJavaClock()
      Returns the underlying Java Clock.
      Returns:
      the Java clock instance