FreezeJ' Blog

python一次性密码库PyOTP

2023-08-14

它是一个能够生成/验证一次性密码(短信验证码)的 Python 库,可以在 Web 应用或其它需要登录的系统上,实现双因素(2FA) 或多因素(MFA) 身份验证方法。

GitHub地址:https://github.com/pyauth/pyotp

安装

pip3 install pyotp

基于时间

import pyotp
import time

totp = pyotp.TOTP('base32secret3232')
totp.now() # => '492039'

# OTP verified for current time
totp.verify('492039') # => True
time.sleep(30)
totp.verify('492039') # => False

基于计数器

import pyotp

hotp = pyotp.HOTP('base32secret3232')
hotp.at(0) # => '260182'
hotp.at(1) # => '055283'
hotp.at(1401) # => '316439'

# OTP verified with a counter
hotp.verify('316439', 1401) # => True
hotp.verify('316439', 1402) # => False
Tags: Python