Skip to content

Instantly share code, notes, and snippets.

@asaph
Created April 25, 2016 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asaph/c06635f7c3e419046e058fcc68b24a59 to your computer and use it in GitHub Desktop.
Save asaph/c06635f7c3e419046e058fcc68b24a59 to your computer and use it in GitHub Desktop.
Calculate the 6-digit 2fa code based on base32 encoded secret key and the current time
public static String getTOTPCode(String secretKey) {
String normalizedBase32Key = secretKey.replace(" ", "").toUpperCase();
Base32 base32 = new Base32();
byte[] bytes = base32.decode(normalizedBase32Key);
String hexKey = Hex.encodeHexString(bytes);
long time = (System.currentTimeMillis() / 1000) / 30;
String hexTime = Long.toHexString(time);
return TOTP.generateTOTP(hexKey, hexTime, "6");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment