Skip to content

Instantly share code, notes, and snippets.

@mjg123 mjg123/
Created Jul 25, 2019

What would you like to do?
Java code demonstrating how to generate HOTP and TOTP codes. Used in my talk 2FA 2Furious
package lol.gilliard;
import com.amdelamar.jotp.OTP;
import com.amdelamar.jotp.type.Type;
// This code uses Austin Delamar's JOTP:
public class Demos {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
private static void hotp() throws NoSuchAlgorithmException, InvalidKeyException {
// Use this to generate the secret when the user first signs up
// String superSecretSecret = OTP.randomBase32(20);
// Assuming a pre-existing user, we have fetched their secret from our DB
String superSecretSecret = "4NHEK6KWH5MVZEXR6M34BCHIC6IQBTOE";
// increment this to generate a new code
String counter = "0";
String hotpCode = OTP.create(superSecretSecret, counter, 6, Type.HOTP);
System.out.println("HOTP code: " + hotpCode);
public static void totp() throws IOException, NoSuchAlgorithmException, InvalidKeyException {
// note as above ^^
// String superSecretSecret = OTP.randomBase32(20);
String superSecretSecret = "4NHEK6KWH5MVZEXR6M34BCHIC6IQBTOE";
String totpCode = OTP.create(superSecretSecret, OTP.timeInHex(), 6, Type.TOTP);
// output changes every 30s
System.out.println("TOTP code: " + totpCode);
// Share the superSecretSecret with the client by generating a QR code from this URL
String url = OTP.getURL(superSecretSecret, 6, Type.TOTP, "2fa2furious", "") + "&label=2FA2Furious";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.