由于公司服务器启用了双因子认证,登录时需要再次输入谷歌身份验证器生成的验证码。而生成验证码是基于固定的算法的,以当前时间为基础,基于每个人的google key去生成一个6位的验证码。也就是说,只要是这个key,只要处于当前这个时间,生成的一定是这6位数字。
以下为python3实现
import hmac import base64 import struct import hashlib import time def cal_google_code(secret_key): duration_input = int(time.time())//30 key = base64.b32decode(secret_key) # Length of the key must be a multiplier of eight msg = struct.pack(">Q", duration_input) google_code = hmac.new(key, msg, hashlib.sha1).digest() o = google_code[19] & 15 google_code = str((struct.unpack(">I", google_code[o:o+4])[0] & 0x7fffffff) % 1000000) if len(google_code) == 5: # Only if length of the code is 5, a zero will be added at the beginning of the code. google_code = '0' + google_code return google_code
这段算法有两个要点。
首先算法对google key的长度是有要求的,key的长度必须是8的倍数。所以如果运维给的key不符合要求,需要在后面补上相应个数的"="。
其次,按照此算法,生成的验证码未必是6位,注意要在前面补0。