php实现TOTP
TOTP 简介
TOTP(Time-based One-Time Password)是一种基于时间的一次性密码算法,常用于双因素认证(2FA)。其核心是结合密钥和当前时间戳生成动态验证码,通常每30秒更新一次。
PHP 实现步骤
依赖安装
确保服务器已安装 PHP 且版本 ≥ 7.1。需通过 Composer 安装 sonata-project/google-authenticator 库:
composer require sonata-project/google-authenticator
生成密钥 使用库生成随机密钥,并转换为 Base32 格式便于用户扫描二维码:
use Sonata\GoogleAuthenticator\GoogleAuthenticator;
$g = new GoogleAuthenticator();
$secret = $g->generateSecret();
生成验证码 基于当前时间戳计算验证码(默认30秒有效):
$code = $g->getCode($secret);
验证用户输入 校验用户提供的验证码是否匹配当前或临近时间段的预期值:
$isValid = $g->checkCode($secret, $userInput);
生成二维码 URL 方便移动端扫描绑定(如 Google Authenticator):

$qrUrl = $g->getUrl('YourAppName', 'user@example.com', $secret);
// 输出为:otpauth://totp/YourAppName:user@example.com?secret=XXX&issuer=YourAppName
完整示例代码
require_once 'vendor/autoload.php';
$g = new \Sonata\GoogleAuthenticator\GoogleAuthenticator();
$secret = $g->generateSecret();
$qrUrl = $g->getUrl('MyApp', 'user123', $secret);
// 模拟用户输入
$userCode = '123456'; // 从表单获取
$isValid = $g->checkCode($secret, $userCode);
echo "Secret: $secret\n";
echo "QR URL: $qrUrl\n";
echo "Valid: " . ($isValid ? 'Yes' : 'No') . "\n";
注意事项
- 时间同步:服务器与客户端需保持时间同步,NTP 服务推荐。
- 密钥存储:密钥需安全存储(如数据库加密字段),不可明文传输。
- 容错窗口:可通过
$g->setCodeLength(6)调整验证码位数(默认6位)。
扩展优化
- 自定义有效期:修改
GoogleAuthenticator类的$timeSlice属性。 - 多设备支持:同一密钥可在多个设备使用,但需注意同步问题。
- 备份代码:生成一组静态备用码供紧急情况使用。






