Python计算谷歌身份验证器(google authenticator)的验证码

来源:互联网 发布:筹备淘宝静物工作室 编辑:程序博客网 时间:2024/05/01 16:54

谷歌身份验证码是继续时间计算的。服务端和客户端各自根据密钥,基于时间计算出6为验证码。

计算的公式是根据网上来的,其中有些代码位数计算出来不对,自己略有修改,代码如下:

(其中,参数secretKey 是开通google身份验证时的密钥)

import hmac, base64, struct, hashlib, time

def calGoogleCode(secretKey):    input = int(time.time())//30    key = base64.b32decode(secretKey)    msg = struct.pack(">Q", input)    googleCode = hmac.new(key, msg, hashlib.sha1).digest()    o = ord(googleCode[19]) & 15    googleCode = str((struct.unpack(">I", googleCode[o:o+4])[0] & 0x7fffffff) % 1000000)    if len(googleCode) == 5:             # 如果验证码的第一位是0,则不会显示。此处判断若是5位码,则在第一位补上0        googleCode = '0' + googleCode    return googleCode


需要注意的是,如果运行py脚本的电脑时间不是基于网络自动调整,那么计算出来的googleCode可能不正确。

阅读全文
0 0
原创粉丝点击