欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-20 08:36:44
由于公司服务器启用了双因子认证,登录时需要再次输入谷歌身份验证器生成的验证码。而生成验证码是基于一套固定的算法的,以当前时间为基础,基于每个人的google key去生成一个6位的验证码 以下为python3实现 首先算法对google key的长度是有要求的。key的长度必须是8的倍数,所以如果运 ......

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