双因素认证指南
TOTP 与 HOTP 对比
| 特性 | TOTP | HOTP |
|---|---|---|
| 标准 | RFC 6238 | RFC 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
| 参数 | 说明 |
|---|---|
| secret | Base32 编码的共享密钥 |
| algorithm | SHA1 (默认), SHA256, SHA512 |
| digits | 6 或 8 |
| period | 30s (默认) |