java-otp 1.0.0 API
java-otp is a Java library for generating HOTP (RFC 4226) or TOTP (RFC 6238) one-time passwords.
Usage
To demonstrate generating one-time passwords, we'll focus on the TOTP algorithm. To create a TOTP generator with a default password length, time step, and HMAC algorithm:
final TimeBasedOneTimePasswordGenerator totp = new TimeBasedOneTimePasswordGenerator();
To actually generate time-based one-time passwords, you'll need a secret key and a timestamp. Secure key management is beyond the scope of this document; for the purposes of an example, though, we'll generate a random key:
final SecretKey key;
{
final KeyGenerator keyGenerator = KeyGenerator.getInstance(totp.getAlgorithm());
keyGenerator.init(160);
key = keyGenerator.generateKey();
}
Armed with a secret key, we can deterministically generate one-time passwords for any timestamp:
final Instant now = Instant.now();
final Instant later = now.plus(totp.getTimeStep());
System.out.println("Current password: " + totp.generateOneTimePasswordString(key, now));
System.out.println("Future password: " + totp.generateOneTimePasswordString(key, later));
To validate a one-time password:
// In a real-world scenario, this might come from an HTTP request or some other remote channel
final int userSuppliedOneTimePassword = 164092;
if (totp.validateOneTimePassword(key, now, userSuppliedOneTimePassword)) {
System.out.println("Password was correct");
} else {
System.out.println("Password was incorrect");
}
Please note that validateOneTimePassword simply checks equality of one-time passwords; compensating for clock drift, throttling/rate-limiting password validation attempts, clock resynchronization, and so on are all beyond java-otp's scope and callers must address those concerns on their own. For more information, please see "TOTP: Time-Based One-Time Password Algorithm (RFC 6238) - Security Considerations" (and "HOTP: An HMAC-Based One-Time Password Algorithm (RFC 4226) - Security Requirements" for HOTP).
License and copyright
java-otp is copyright (c) 2016 Jon Chambers and available under the MIT License.