【发布时间】:2021-09-23 05:56:11
【问题描述】:
我正在尝试实现 TOTP,但我遇到了问题,因为 Google Authenticator 输出的 Token 与此处计算的结果不匹配。
开发环境:Java(Servlet) Eclipse
-
生成密钥
我使用 Google 身份验证通过 key.getKey () 从我的用户名生成密钥,并使用 Base32 () 对其进行编码。
final GoogleAuthenticatorKey key = gAuth.createCredentials( userName ); key.getKey() Use Apache Base32() -
生成二维码
生成二维码。另见图片。
<script src="/js/qrcode.min.js"></script> otpauth://totp/takao.ehara? secret=IU3U2U2SINBEQWSWJNCUINC2KVLEMSKYLFLFCNRUJ5JTMS2RLBKQ& issuer=Takao Ehara Corporation&digits=6&period=30 -
使用 iPhone 的 google 身份验证器获取令牌。
log : Token = 723025 -
HMAC_SHA256
使用基于密钥的SHA256算法生成哈希。
log : HS = HMAC-SHA-1( K, C ) : K = IU3U2U2SINBEQWSWJNCUINC2KVLEMSKYLFLFCNRUJ5JTMS2RLBKQ Variables : K = secretKey SecretKeySpec sks = new SecretKeySpec( secretKey, HMAC_SHA256 ); Mac mac = Mac.getInstance( HMAC_SHA256 ); mac.init(sks); byte[] hmacBytes = mac.doFinal(); return hmacBytes; -
结果字符串
生成的HASH如下。
Variables : HS = hmacBytes HS = 3c72f2b3802ab9b8a210ea992c436683ddd73c6a9cf55bfcb30921e7b359e1e4 -
结果 = 514302
另请参阅:RFC 4226 - HOTP
The hash length is 32. log : hash.length = 32 Hash, get the lower 4 bits of the 32nd byte. HS = 3c72f2b3802ab9b8a210ea992c436683ddd73c6a9cf55bfcb30921e7b359e1e [4]在这种情况下,偏移量是 4。
log : offset = 4从哈希的第 4 个字节中获取 4 个字节。
HS = 3c72f2b3 [802ab9b8] a210ea992c436683ddd73c6a9cf55bfcb30921e7b359e1e4 log : e = 8 0 2 a b 9 b 8OR 每个字节。
long e0 = numeric[0] << 28; long e1 = numeric[1] << 24; long e2 = numeric[2] << 20; long e3 = numeric[3] << 16; long e4 = numeric[4] << 12; long e5 = numeric[5] << 8; long e6 = numeric[6] << 4; long e7 = numeric[7] << 0; // e0 = 8, e1 = 0, e2 = 2, e3 = a, e4 = b, e5 = 9, e6 = b, e7 = 8 long truncate = (long)( e0 | e1 | e2 | e3 | e4 | e5 | e6 | e7 ); log : truncate = 2150283704我会把源代码放在下一行。
*********************** // HOTP computation for Digit = 6 // D = Snum modulo 10 ^ 6 long pow = (long)Math.pow( 10, 6 ); long hotp = (long)( truncate % pow ); // zero press String totp = String.format( "%06d", (int)hotp ); *********************** -
不匹配。
Token = 723025(from Google Authenticator) result = 514302(this)
【问题讨论】:
-
我不知道你为什么会得到反对票和接近票数,这是个好问题。