2018年8月9日 星期四

[JAVA] Google Authenticator 2FA Implementation / TOTP

Library / file required:

Apache Commons Codec

https://commons.apache.org/proper/commons-codec/download_codec.cgi


Download TOTP.java

https://tools.ietf.org/html/rfc6238


Put TOTP.java and Test.java together and run.

Good luck.



import org.apache.commons.codec.binary.Base32;
import org.apache.commons.codec.binary.Hex;

public class Test {
 public static void main(String[] args) {
  String seed = "JBSWY3DPEHPK3PXP";
  System.out.println(getTOTPCode(seed));
 }

 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");
 }

}

沒有留言:

張貼留言