当前位置: 移动技术网 > IT编程>脚本编程>Python > time-based基于google key生成6位验证码(google authenticator)

time-based基于google key生成6位验证码(google authenticator)

2018年12月07日  | 移动技术网IT编程  | 我要评论

脚趾甲变厚变黄,小学生成语故事大全,哑巴皇后要训夫

由于公司服务器启用了双因子认证,登录时需要再次输入谷歌身份验证器生成的验证码。而生成验证码是基于一套固定的算法的,以当前时间为基础,基于每个人的google 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。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网