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

谷歌身份验证码是继续时间计算的。服务端和客户端各自根据密钥,基于时间为30秒为验证码,网上搜了很多,一直报错,还是看我同事何泽

解决报错TypeError: Incorrect padding 的问题,因为秘钥不是8的倍数,需要用“=”补足,不知道为啥网上资料这么难搜索

import hmac, base64, struct, hashlib, time

def calGoogleCode(secretKey):
    input = int(time.time())//30
    lens = len(secretKey)
    lenx = 8 - (lens % 4 if lens % 4 else 4)
    secretKey += lenx * '='
    print secretKey, ' ----- ' ,lenx  , lens ,'|'
    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:
        googleCode = '0' + googleCode
    return googleCode

你可能感兴趣的:(Python随手笔记)