Created
July 25, 2019 11:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", "[email protected]") + "&label=2FA2Furious"; | |
System.out.println(url); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment