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。

  • 相关阅读:
    POJ2785-4 Values whose Sum is 0
    Codeforce 9C
    Codeforces 797C -Minimal string
    程序员自我修养
    异或
    Socket网络编程
    java编写本月日历
    PreparedStatement的用法
    项目导入时报错:The import javax.servlet.http.HttpServletRequest cannot be resolved 解决方法
    Dell灵越 5559笔记本安装固态硬盘 BIOS设置
  • 原文地址:https://www.cnblogs.com/wuhuohanke/p/10082401.html
Copyright © 2011-2022 走看看