zoukankan      html  css  js  c++  java
  • python3计算谷歌验证码

    1. 问题
    使用python3计算谷歌验证码(16位谷歌秘钥,生成6位验证码。基于时间,每30s更新1次)
    2. 代码

    import hmac, base64, struct, hashlib, time


    class CalGoogleCode():
    """计算谷歌验证码(16位谷歌秘钥,生成6位验证码)"""

    # 使用静态方法,调用这个方法时,不必对类进行实例化
    @staticmethod
    def cal_google_code(secret, current_time=int(time.time()) // 30):
    """
    :param secret: 16位谷歌秘钥
    :param current_time: 时间(谷歌验证码是30s更新一次)
    :return: 返回6位谷歌验证码
    """
    key = base64.b32decode(secret)
    msg = struct.pack(">Q", current_time)
    google_code = hmac.new(key, msg, hashlib.sha1).digest()
    o = ord(chr(google_code[19])) & 15 # python3时,ord的参数必须为chr类型
    google_code = (struct.unpack(">I", google_code[o:o + 4])[0] & 0x7fffffff) % 1000000
    return '%06d' % google_code # 不足6位时,在前面补0


    if __name__ == '__main__':
    secret_key = "ABCDEFGHIJKLMNOP"
    print(CalGoogleCode.cal_google_code(secret_key)) # 并未实例化CalGoogleCode,也可以调用它的方法
    3. 注意
    这是基于时间更新谷歌验证码,因此需要保证电脑上的时间准确。
  • 相关阅读:
    git 常用命令
    PHP打印日志类
    如何从总账获取分类账信息
    AP -> GL 数据流动
    JDeveloper 速度慢问题
    JDeveloper 滚轮不受控制
    MyBatis 环境搭建
    初识 MyBatis
    Linux 中设置 MySQL 字符集为 UTF-8
    Linux 安装 MySQL 详解(rpm 包)
  • 原文地址:https://www.cnblogs.com/lipx9527/p/13933284.html
Copyright © 2011-2022 走看看