Generating an TOTP

In this post I will show with example how to generate TOTP.

TOTP is based on HOTP but instead of using counter, TOTP uses the current time as the counter in addition to secret key

So TOTP = HOTP(secret key, current time).

Similar to HOTP in client server scenario both client and server has to share the secret key and instead of keeping track of counter they can use current time
as the counter.

Below is the complete code used to generate TOTP

Main class

1  package defaultPackage;
2
3 import com.bastiaanjansen.otp.SecretGenerator;
4 import com.bastiaanjansen.otp.TOTP;
5
6 public class Example5 {
7 public static void main(String[] args) {
8 byte[] secret = SecretGenerator.generate();
9 TOTP.Builder builder = new TOTP.Builder(secret);
10 TOTP totp = builder.build();
11 System.out.println(totp.now());
12 }
13 }

In the above code, at line 8, we are generating a symmetric key.

At line 9 we are creating a builder instance of “TOTP.Builder” class named “builder” and passing the secret key as argument.

At line 10, we are creating an instance of “TOTP” class by calling “build” method on builder instance.

At the last, we generate the totp by calling “now” method on “TOTP” instance and printing it to the console.

Leave a comment