zoukankan      html  css  js  c++  java
  • Python计算谷歌身份验证器(google authenticator)的验证码

    1、安装插件:pip install onetimepass

    2、代码:

    import hmac, base64, struct, hashlib, time
    import sys
        
    def calGoogleCode(secretKey):
        input = int(time.time()) // 30
        key = base64.b32decode(secretKey)
        msg = struct.pack(">Q", input)
        googleCode = hmac.new(key, msg, hashlib.sha1).digest()
        #版本判断
        if (sys.version_info> (2, 7)):
            o = googleCode[19] & 15
        else:
            o = ord(googleCode[19]) & 15
        googleCode = str((struct.unpack(">I", googleCode[o:o + 4])[0] & 0x7fffffff) % 1000000)
        if len(googleCode) == 5:  # 如果验证码的第一位是0,则不会显示。此处判断若是5位码,则在第一位补上0
            googleCode = '0' + googleCode
        return googleCode
            
    print(calGoogleCode("密钥"))
    time.sleep(5)
    

    验证码错误可能原因:
    1、本地时间与实际时间偏差过大,结果可能不正确。
    解决方案:同步网络时间,或手动校正
    2、以上代码只能处理16位验证码,若其他位数验证码需调整index计算位数
    3、秘钥不是8的倍数,需要用“=”补足

    参考网址:参考1   参考2

  • 相关阅读:
    B/S 和 C/S
    SQL 注入
    软件测试
    Spring的注解方式
    测试开发题目
    策略模式
    设计模式
    单例模式
    读写文件
    对List里的对象元素进行排序
  • 原文地址:https://www.cnblogs.com/wangle/p/15770837.html
Copyright © 2011-2022 走看看