Generating HOTP example

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

I will be using open source otp framework written by “BastiaanJansen” using Java programming language.

Below is the link to the GitHub project

https://github.com/BastiaanJansen/otp-java

HOTP is generated using two input parameters
1) a secret
2) a counter

Below is the main method that shows how to generate hotp.

Main class

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

In the above code, at line 10 we are generating the secret symmetric key.

At line 11, we are creating builder object named “builder” using the secret which will help us creating an instance of “HOTP” class.

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

Then at line 13 we generate otp by calling “generate” method on “hotp” instance and passing the counter as an argument.

Internally the framework by default uses SHA-1 algorithm to generate otp.

At line 14, we print the otp.

In this way we can generate an HOTP using the framework.

Below is the output

Output

314084

Leave a comment