Python: 使用pyotp实现OTP一次性密码验证

使用pyotp实现OTP一次性密码验证

OTP的基本原理

  1. 生成一个共享秘钥作为随机数的种子
  2. 服务端通过种子计算出当前的密码
  3. 客户端也通过相同的种子计算出当前的密码
  4. 验证客户端生成的密码和服务端生成的密码是否匹配

服务端和客户端计算的方式一样

复制代码
共享密钥 + 时间因子 + 算法 => 密码结果

文档

安装

bash 复制代码
pip install pyotp

基本使用示例

python 复制代码
import pyotp

# 秘钥
secret_key = 'S5MPVVK6TYBAYJTKEWW5UGDSC2NX6OPS'

totp = pyotp.TOTP(secret_key)

# 生成一个随机密码
totp.now()  # => '492039'

# 验证
totp.verify('198361') # 返回 True或False

秘钥有一定的规则,可以使用pyotp提供的方法生成一个随机秘钥

bash 复制代码
secret_key = pyotp.random_base32()  # S5MPVVK6TYBAYJTKEWW5UGDSC2NX6OPS

生成一个url,使用Google Authenticator扫描

python 复制代码
# 生成一个url,使用Google Authenticator扫描
print(totp.provisioning_uri(name='alice@google.com', issuer_name='Secure App'))
# otpauth://totp/Secure%20App:alice%40google.com?secret=S5MPVVK6TYBAYJTKEWW5UGDSC2NX6OPS&issuer=Secure%20App

比如使用https://cli.im/text 生成二维码如下

参考

相关推荐
码途行者7 小时前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang
头发还在的女程序员7 小时前
Java充电桩平台源码解析:枪口状态、上报时间与页面刷新怎样协同
java·开发语言·充电桩系统·充电桩管理·充电系统·充电小程序
timeDifference₇9 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu10 小时前
python:DecisionTree
开发语言·后端·python·算法
怒放的生命199111 小时前
代码知识库 RAG 问答系统 —— 从 0 到 1 实现教程
python·状态模式·fastapi·全栈开发·ai agent应用开发
geovindu11 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
Flynn Liang12 小时前
全栈实战:从零搭建一套可落地的生产级 AI 智能体系统(Redis 版)
人工智能·redis·ai agent
fengkai454512 小时前
Python运维
运维·python·监控·psutil·ipy
Fancy.76112 小时前
:Python条件与循环语句学习总结
python
Wellijohn14 小时前
Python 容器选型实测:list.insert(0) 慢 925 倍,in 慢 6000 倍
python