我目前正在尝试重新创建 Google 一次性密码生成器。我使用设置 Google Authenticator 时生成的共享密钥。我尝试查看 Google Authenticator 的来源和互联网上的所有内容,我发现我的代码有很多相似之处,但我真的找不到我错的地方。第一部分似乎是正确的。至于 hmac,我认为我不能在这里搞砸,但我可能错了。截断部分对我来说仍然有点模糊,我尝试了很多不同的实现,但我就是无法获得有效的 OTP。(我正在使用 Google Authenticator 来比较结果)
private String truncateHash(byte[] hash) {
int offset = hash[hash.length - 1] & 0xF;
long truncatedHash = 0;
for (int i = 0; i < 4; ++i) {
truncatedHash <<= 8;
truncatedHash |= (hash[offset + i] & 0xFF);
}
truncatedHash &= 0x7FFFFFFF;
truncatedHash %= 1000000;
int code = (int) truncatedHash;
String result = Integer.toString(code);
for (int i = result.length(); i < 6; i++) {
result = "0" + result;
}
return result;
}
private byte[] hmacSha1(byte[] value, byte[] keyBytes) {
try {
Mac mac = HmacUtils.getHmacSha1(keyBytes);
byte[] rawHmac = mac.doFinal(value);
return new Hex().encode(rawHmac);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String GoogleAuthenticatorCode(String secret) throws UnsupportedEncodingException {
Base32 base = new Base32();
byte[] key = base.decode(secret);
//Update from Andrew Rueckert's response
long value = new Date().getTime() / TimeUnit.SECONDS.toMillis(30);
byte[] data = new byte[8];
for (int i = 8; i-- > 0; value >>>= 8) {
data[i] = (byte) value;
}
//
System.out.println("Time remaining : " + new Date().getTime() / 1000 % 30);
byte[] hash = hmacSha1(data, key);
return truncateHash(hash);
}
更新:我尝试从 Andrew Rueckert 的响应链接以及这个https://github.com/wstrange/GoogleAuth/blob/master/src/main/java/com/warrenstrange/googleauth/GoogleAuthenticator.java
和来自RFC 4226
. 这些都没有给我一个正确的OTP
任何人都可以启发我吗?