我正在尝试使用Google Authenticator 应用程序生成一次性密码。
Google Authenticator的功能
基本上,Google Authenticator 实现了两种类型的密码:
- HOTP - 基于HMAC的一次性密码,这意味着每次调用时密码会更改,符合RFC4226的规定,以及
- TOTP - 基于时间的一次性密码,每30秒更改一次(就我所知)。
Google Authenticator也可以在这里作为开源获得:code.google.com/p/google-authenticator
当前代码
我正在寻找现有的解决方案来生成HOTP和TOTP密码,但没有找到太多资料。我拥有的代码是以下片段,负责生成HOTP:
import hmac, base64, struct, hashlib, time
def get_token(secret, digest_mode=hashlib.sha1, intervals_no=None):
if intervals_no == None:
intervals_no = int(time.time()) // 30
key = base64.b32decode(secret)
msg = struct.pack(">Q", intervals_no)
h = hmac.new(key, msg, digest_mode).digest()
o = ord(h[19]) & 15
h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
return h
我面临的问题是,我使用上述代码生成的密码与Google Authenticator Android应用程序生成的密码不同。尽管我尝试了多个 intervals_no 值(恰好前10000个值,以 intervals_no = 0 开始),其中 secret 等于 GA 应用程序提供的密钥。我的问题如下:
- 我做错了什么?
- 如何在 Python 中生成 HOTP 和/或 TOTP?
- 是否存在此类Python库?
casefold=True
,所以现在人们不应该再遇到类似的问题了。感谢您的建议。 - Tadeckord(h[19]) & 15
改为o = h[19] & 15
。 - Orvillereturn '{:06}'.format(h)
替换return h
。 - Noam