Class TOTPClock
java.lang.Object
io.github.pratiyush.totp.internal.TOTPClock
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 Summary
Modifier and TypeMethodDescriptionlongReturns the current Unix timestamp in seconds.static TOTPClockCreates a clock fixed at the specified instant.static longgetCounterForInstant(Instant instant, int periodSeconds) Returns the counter value for a specific timestamp.longgetCurrentCounter(int periodSeconds) Returns the current TOTP counter value.Returns the underlying Java Clock.intgetSecondsRemaining(int periodSeconds) Returns the number of seconds remaining in the current period.now()Returns the current time as an Instant.static TOTPClockCreates a clock from a Java Clock instance.static TOTPClockCreates a clock using the system UTC time.
-
Method Details
-
systemUTC
Creates a clock using the system UTC time.- Returns:
- system UTC clock
-
fixed
Creates a clock fixed at the specified instant.Useful for testing with specific timestamps.
- Parameters:
instant- the fixed time- Returns:
- fixed clock
-
of
Creates a clock from a Java Clock instance.- Parameters:
clock- the clock to use- Returns:
- TOTP clock wrapper
-
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
Returns the counter value for a specific timestamp.- Parameters:
instant- the timestampperiodSeconds- 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
Returns the underlying Java Clock.- Returns:
- the Java clock instance
-