Changing the algorithm when generating totp

In previous post, I showed with example how to generate an TOTP.

I also mentioned in my previous post, how the framework by default using SHA-1 algorithm to generate the totp.

In this post under OTP, I will show with example how to change the default algorithm.

Below is the code for your reference.

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

In the above code, at line 9 we generate a secret.

At line 10 we create an instance of builder object named “builder” and pass the secret as an argument.

At line 11, we change the algorithm to use from SHA-1 to SHA-512 by calling “withAlgorithm” method on the builder object.

At line 12, we create an instance of TOTP class by calling “build” method on the builder instance.

At line 13, we call “now” method. This will generate an totp which we print to the console.

In this way we can change the algorithm used in generating TOTP.

Leave a comment