Changing the algorithm when generating hotp

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

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

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

Below is the code for your reference.

Main class

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

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 HOTP class by calling “build” method on the builder instance.

At line 13, we call “generate” method passing the counter as an argument. This will generate an hotp which we print at line 14.

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

Leave a comment