双因素认证指南

TOTP 与 HOTP 对比

特性TOTPHOTP
标准RFC 6238RFC 4226
基础时间(30秒窗口)计数器
应用场景Google Auth、Authy硬件令牌
有效期30s使用后失效

实现示例

npm install otplib const { authenticator } = require('otplib'); // 生成密钥 const secret = authenticator.generateSecret(); console.log('Secret:', secret); // 生成二维码 URL const otpauth = authenticator.keyuri('user@example.com', 'MyApp', secret); // 验证令牌 const token = authenticator.generate(secret); const isValid = authenticator.verify({ token, secret });
pip install pyotp qrcode import pyotp, qrcode # 生成密钥 secret = pyotp.random_base32() # TOTP totp = pyotp.TOTP(secret) print(totp.now()) # 当前验证码 print(totp.verify('123456')) # 验证 # 二维码 URL uri = totp.provisioning_uri("user@example.com", issuer_name="MyApp")
go get github.com/pquerna/otp/totp import "github.com/pquerna/otp/totp" // 生成密钥 key, _ := totp.Generate(totp.GenerateOpts{ Issuer: "MyApp", AccountName: "user@example.com", }) // 验证码 valid := totp.Validate(code, key.Secret())

二维码 otpauth:// 格式

otpauth://totp/LABEL?secret=SECRET&issuer=ISSUER&algorithm=SHA1&digits=6&period=30
参数说明
secretBase32 编码的共享密钥
algorithmSHA1 (默认), SHA256, SHA512
digits6 或 8
period30s (默认)