zoukankan      html  css  js  c++  java
  • time-based基于google key生成6位验证码(google authenticator)

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

  • 相关阅读:
    ajax请求传参数复杂对象list,后端springmvc接收参数
    SpringBoot热部署简介
    lucene 初探
    学生管理系统导包
    tomcat加入系统服务+开机自启
    sql like模糊查询的条件拼接
    SSHDemo
    Spring在web开发中的应用
    Spring的Bean内部方法调用无法使用AOP切面(CacheAble注解失效)
    dwz tree组件 取得所选择的值
  • 原文地址:https://www.cnblogs.com/wuhuohanke/p/10082401.html
Copyright © 2011-2022 走看看