Created
October 13, 2012 01:34
-
-
Save anonymous/3882838 to your computer and use it in GitHub Desktop.
Google Authenticator In java
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
public class TOTPassword { | |
public static String createGoogleAuthenticatorURI(String user, String host, | |
String secret) { | |
return new StringBuilder("otpauth://totp/").append(user.toLowerCase().trim()) | |
.append("@") | |
.append(host.toLowerCase().trim()) | |
.append("?secret=") | |
.append(secret.toUpperCase().trim()) | |
.toString(); | |
} | |
public static String createSecretToken() { | |
byte[] buffer = new byte[20]; | |
new Random().nextBytes(buffer); | |
byte[] secretKey = Arrays.copyOf(buffer, 10); | |
return Base32.encode(secretKey); | |
} | |
public static boolean validate(String secret, long code, long count, int margin) | |
throws NoSuchAlgorithmException, InvalidKeyException { | |
byte[] decodedKey = Base32.decode(secret); | |
for (int i = -margin; i <= margin; ++i) { | |
long hash = verificationHash(decodedKey, count + i); | |
if (hash == code) { | |
return true; | |
} | |
} | |
return false; | |
} | |
public static boolean validateGoogleAuthenticator(String secret, long code) | |
throws NoSuchAlgorithmException, InvalidKeyException { | |
return validate(secret, code, System.currentTimeMillis() / 30000, 3); | |
} | |
public static int verificationHash(String secret, long count) | |
throws NoSuchAlgorithmException, InvalidKeyException { | |
return verificationHash(Base32.decode(secret), count); | |
} | |
public static int verificationHash(byte[] decodedSecret, long count) | |
throws NoSuchAlgorithmException, InvalidKeyException { | |
byte[] data = new byte[8]; | |
long value = count; | |
for (int i = 8; i-- > 0; value >>>= 8) { | |
data[i] = (byte) value; | |
} | |
SecretKeySpec signKey = new SecretKeySpec(decodedSecret, "HmacSHA1"); | |
Mac mac = Mac.getInstance("HmacSHA1"); | |
mac.init(signKey); | |
byte[] hash = mac.doFinal(data); | |
int offset = hash[19] & 0xF; | |
long truc = 0; | |
for (int i = 0; i < 4; ++i) { | |
truc <<= 8; | |
truc |= (hash[offset + i] & 0xFF); | |
} | |
truc &= 0x7FFFFFFF; | |
truc %= 1000000; | |
return (int) truc; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment