python接入GoogleAuth的实现
更新时间:2023年08月07日 09:15:47 作者:SeasonRun
经常会用到GoogleAuth作为二次验证码,本文主要介绍了python接入GoogleAuth的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
经常会用到GoogleAuth作为二次验证码,就扒了代码看看这块逻辑如何实现的,做个笔记。
import hmac
import struct
import time
from hashlib import sha1
from urllib.parse import urlencode, quote
if __name__ == '__main__':
# account会作为标识显示在身份验证器上
account = input("please enter your account: ")
# secret用于生成秘钥
secret = input("please enter your secret: ")
# label会作为标识显示在身份验证器上
label = input("please enter your label: ")
# 将secret转换成bytes
s = secret.encode()
# 获取时间片(1990年1月1日0时开始计时,30秒为一个单位)
c = struct.pack(">Q", int(time.time()) // 30)
# 根据secret和时间片指定sha1算法计算hash值,返回bytes类型hash值
hmac_hash = hmac.new(s, c, sha1).digest()
print("hmac_hash:", len(hmac_hash))
# 取出hmac_hash的第19位和0xf做”与“运算
offset = hmac_hash[19] & 0xf
print("offset:", offset)
# 从hmac_hash中取出4个16进制字节转换为正整数(I)并取索引为[0],再与16进制0x7fffffff做与运算,最后除以10的六次方
google_code = (struct.unpack(">I", hmac_hash[offset: offset + 4])[0] & 0x7fffffff) % 10 ** 6
print(google_code)
# 若计算后结果不足6位, 则在左侧补0
google_code = f'{google_code:>06}'
print(google_code)
prefix = label
prefix += f':{account}'
ends = {
'secret': secret,
'label': label
}
base_uri = 'otpauth://totp/{prefix}?{ends}'
# 调用草料二维码生成api
caoliao_qrcode_url = 'https://api.pwmqr.com/qrcode/create/?url={qr_content}'
qr_uri = base_uri.format(prefix=prefix, ends=urlencode(ends))
print(caoliao_qrcode_url.format(qr_content=quote(qr_uri)))使用谷歌身份验证器扫描链接生成的二维码即可绑定。

到此这篇关于python接入GoogleAuth的实现的文章就介绍到这了,更多相关python接入GoogleAuth内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:
相关文章
python报错TypeError: Input z must be
大家好,本篇文章主要讲的是python报错TypeError: Input z must be 2D, not 3D的解决方法,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下2021-12-12
使用Selenium控制当前已经打开的chrome浏览器窗口
有时通过selenium打开网站时,发现有些网站需要扫码登录,就很头疼,导致爬虫进展不下去,下面这篇文章主要给大家介绍了关于使用Selenium控制当前已经打开的chrome浏览器窗口的相关资料,需要的朋友可以参考下2022-07-07
Python报错KeyError: ‘missing_key‘的有效解决方法
在 Python 编程中,报错信息常常让开发者感到困扰,其中,“KeyError: ‘missing_key’”是一个较为常见的报错,它可能在各种数据处理和字典操作的场景中出现,本文将深入探讨这个报错的原因,并提供多种有效的解决方法,帮助开发者快速解决此类问题2024-10-10


最新评论