Verifying the TOTP

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

In my previous posts, under OTP I showed with example how to generate TOTP.

To verify an TOTP we can use non-static overloaded “verify” methods in “TOTP” class.

Below is the complete code for your reference.

Main Class

1  package defaultPackage;
2
3 import com.bastiaanjansen.otp.SecretGenerator;
4 import com.bastiaanjansen.otp.TOTP;
5
6 public class Example7 {
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 String otp = totp.now();
12 System.out.println(otp);
13 System.out.println(totp.verify(otp));
14 }
15 }

In the above code at line 11, we generate the totp.

At line 13, we verify the totp by calling “verify” method, passing the otp as an arguments.

In a client server scenario, the secret has to be shared between client and server.

In this way we can verify the generated totp.

Leave a comment