Skip to content

Instantly share code, notes, and snippets.

@mjg123
Created July 25, 2019 11:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjg123/78214fd7793bc3db2552b839f5487000 to your computer and use it in GitHub Desktop.
Save mjg123/78214fd7793bc3db2552b839f5487000 to your computer and use it in GitHub Desktop.
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;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
// This code uses Austin Delamar's JOTP: https://github.com/amdelamar/jotp
public class Demos {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
hotp();
totp();
}
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", "matthew.gilliard@gmail.com") + "&label=2FA2Furious";
System.out.println(url);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment