1、安装插件:pip install onetimepass
2、代码:
import hmac, base64, struct, hashlib, time
import sys
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()
#版本判断
if (sys.version_info> (2, 7)):
o = googleCode[19] & 15
else:
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
print(calGoogleCode("密钥"))
time.sleep(5)
验证码错误可能原因:
1、本地时间与实际时间偏差过大,结果可能不正确。
解决方案:同步网络时间,或手动校正
2、以上代码只能处理16位验证码,若其他位数验证码需调整index计算位数
3、秘钥不是8的倍数,需要用“=”补足