Google双因子认证python最好的

发布时间:2019-09-08 09:11:38编辑:auto阅读(1632)

    这个版本应该是最好的实现,在这个上面增加四个时间点,可以用in方式进行判断避免出错。

    @代码的注释其实就是最好的说明

    class _GoogleTwoSetpAuth(object):
        '''Google令牌二次认证相关'''
    
        def _get_hotp_token(self, secret, intervals_no):
            '''获取htop_token 内部方法 算法
            :param secret 二次验证前的编码
            :param intervals_no 时间间隔
            '''
            key = base64.b32decode(secret, True)
            msg = struct.pack(">Q", intervals_no)
            h = hmac.new(key, msg, hashlib.sha1).digest()
            o = ord(h[19]) & 15
            h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
            return h
    
        def get_totp_token(self, secret):
            '''获取totop
            :param secret 二次验证前的编码, 调用这个方法
            '''
    
            # 时间样本
            t     = time.time()
            t_30  = t + 30
            t_30_ = t -30
            t_60  = t - 60
    
            # 90s 的时间, 一般客户端时间差不会超过这个,超过这个不提供方法
            oold = self._get_hotp_token(secret, intervals_no=int(t_60) // 30)
            old = self._get_hotp_token(secret, intervals_no=int(t_30_)//30)
            now = self._get_hotp_token(secret, intervals_no=int(t)//30)
            new = self._get_hotp_token(secret, intervals_no=int(t_30)//30)
            return oold, old, now, new
    
        def shutff_str(self):
            '''生成随机字符串大字16位'''
            src = "abcdefghijklmnopqrstuvwxyz".upper()
            secret= "".join(random.sample(src,16)).replace(' ','')
            return secret

关键字