remotemerge/totp-php
GitHub: remotemerge/totp-php
一个轻量级、零依赖的 PHP TOTP 库,帮助开发者快速为应用集成符合 RFC 标准的双因素认证功能。
Stars: 22 | Forks: 4
# **TOTP PHP:终极 PHP 2FA 库**
[](https://github.com/remotemerge/totp-php)
[](https://github.com/remotemerge/totp-php)
[](https://github.com/remotemerge/totp-php)
[](https://sonarcloud.io/summary/overall?id=totp-php&branch=main)
[](https://sonarcloud.io/summary/overall?id=totp-php&branch=main)
[](https://packagist.org/packages/remotemerge/totp-php)
[](https://github.com/remotemerge/totp-php?tab=MIT-1-ov-file)

## **目录**
| # | 标题 | 描述 |
|----|-----------------------------------------|-----------------------------------------------------------------------------|
| 1 | [为什么选择 TOTP PHP?](#why-choose-totp-php) | 非常适合安全登录、数据保护和增强用户安全性。 |
| 2 | [核心特性](#key-features) | 安全的密钥生成、多算法支持、QR 码和自定义设置。 |
| 3 | [兼容性](#compatibility) | 与所有主要的身份验证器应用和兼容 RFC 的工具无缝协作。 |
| 4 | [快速入门](#get-started-in-minutes) | 通过 Composer 快速安装并提供简单的使用示例。 |
| 5 | [基本用法](#basic-usage) | 生成密钥、TOTP 验证码、验证验证码以及创建 QR 码 URI。 |
| 6 | [自定义配置](#customization-options) | 更改哈希算法、验证码长度和时间切片持续时间。 |
| 7 | [高级用法](#advanced-usage) | 重放保护、密钥审计、偏差限制和 QR 码。 |
| 8 | [使用 Docker 体验](#try-with-docker) | 使用 Docker 进行本地测试,实现快速设置。 |
| 9 | [不使用 Docker 体验](#try-with-php) | 使用 PHP 内置服务器进行轻量级的本地测试。 |
| 10 | [获取帮助](#getting-help) | 报告 Bug、获取集成帮助或进行项目协作。 |
| 11 | [贡献指南](#contribution) | 遵循编码规范、测试代码并提交 Pull Request。 |
| 12 | [项目截图](#screenshots) | 库实际运行的视觉演示。 |
## **为什么选择 TOTP PHP?**
TOTP PHP 是一个多功能、安全且可靠的 PHP TOTP 库,可轻松集成 2FA。这个对开发者友好、轻量级且安全的库,为安全登录系统、数据保护和增强用户安全性提供了简便性、高性能和自定义能力。TOTP PHP 专为现代 PHP 开发者设计,在确保强大保护的同时兼顾易用性和高性能。
## **核心特性**
✅ **安全的密钥生成**
为 TOTP 生成密码学安全的密钥,确保最高级别的安全性。
✅ **QR 码集成**
生成符合标准的 **otpauth URIs**,用于在 Google Authenticator、Microsoft Authenticator、Authy 等身份验证器应用中进行 QR 码设置。
✅ **可自定义的验证码长度**
生成 **6 位或 8 位** 的 TOTP 验证码,可根据应用需求进行配置。
✅ **时间切片配置**
可配置的时间切片持续时间(例如 **30 或 60 秒**),以匹配安全需求。
✅ **偏差验证**
在验证 TOTP 验证码时允许 **时间切片偏差**,确保流畅的用户体验。这对于处理时钟漂移特别有用。
✅ **重放攻击防护**
`verifyCodeOnce()` 方法通过跟踪上次接受的时间切片,防止重用已被接受的验证码,从而消除重放攻击途径。
✅ **密钥安全审计**
`auditSecret()` 方法可检查密钥并返回其解码后的字节长度、强度评级和可操作的警告 —— 而不会抛出异常。
✅ **偏差范围强制限制**
偏差参数会针对可配置的上限(默认值:10)进行验证,防止配置错误或恶意值无限扩大验证窗口。
✅ **便捷验证**
通过 **简单直观的 API** 验证 TOTP 验证码,让集成变得十分简单。
✅ **轻量且快速**
专为性能而构建,TOTP PHP **轻量级** 且经过速度优化,确保最小的开销。
✅ **开发者友好**
TOTP PHP 充分考虑了开发者的使用体验,**易于使用**,文档完善且经过了全面测试。
## **兼容性**
TOTP PHP 基于 **通用标准** 构建,可与全球 **所有主要的身份验证器应用** 无缝协作。无论用户偏好移动应用、桌面工具还是硬件 Token,此库都能确保在整个生态系统中实现完美的兼容性。
### **支持的身份验证器应用**
| 📱 **移动端验证器** | 💻 **桌面与硬件** |
|------------------------------|---------------------------|
| ✅ Google Authenticator | ✅ YubiKey Authenticator |
| ✅ Microsoft Authenticator | ✅ FreeOTP |
| ✅ Authy | ✅ OTP Auth (iOS) |
| ✅ Duo Mobile | ✅ Aegis Authenticator |
| ✅ 1Password | ✅ andOTP |
| ✅ LastPass Authenticator | ✅ 任何兼容 RFC 的工具 |
| ✅ Bitwarden Authenticator | |
### **标准合规性**
🔒 **兼容 RFC 的实现**
TOTP PHP 遵循 **RFC 6238** 标准实现基于时间的一次性密码,将密钥验证为带有有效填充的大写 **RFC 4648 Base32** 格式,并生成兼容 **Key URI Format** 的 `otpauth://` URI。测试套件包含了适用于 SHA1、SHA256 和 SHA512 的 RFC 6238 附录 B 测试向量。
## **几分钟内快速入门**
将 TOTP PHP 添加到项目中非常快速简便。该库要求 **PHP 8.1** 或更高版本。
### **安装**
通过 Composer 安装此库:
```
composer require remotemerge/totp-php
```
## **基本用法**
### **生成密钥**
```
use RemoteMerge\Totp\TotpFactory;
// Create a new TOTP instance
$totp = TotpFactory::create();
// Generate a new secret key for the user
$secret = $totp->generateSecret();
// Output the secret key
echo "Generated Secret Key: $secret\n";
```
**输出:**
```
Generated Secret Key: MHYPSU6HI7UUMFTQD24XVUUQR7JLKV6Y
```
`generateSecret()` 会创建一个 20 字节的随机密钥,并编码为大写的 Base32 格式。从其他系统导入密钥时,请使用 `auditSecret()` 检查解码后的长度和格式,然后再进行存储。
### **生成 TOTP 验证码**
```
use RemoteMerge\Totp\TotpFactory;
// Create a new TOTP instance
$totp = TotpFactory::create();
// Example 20-byte Base32 secret
$secret = 'MHYPSU6HI7UUMFTQD24XVUUQR7JLKV6Y';
// Generate a TOTP code
$code = $totp->getCode($secret);
echo "Generated TOTP Code: $code\n";
```
**输出:**
```
Generated TOTP Code: 123456
```
### **验证 TOTP 验证码**
```
use RemoteMerge\Totp\TotpFactory;
// Create a new TOTP instance
$totp = TotpFactory::create();
// Example 20-byte Base32 secret and code
$secret = 'MHYPSU6HI7UUMFTQD24XVUUQR7JLKV6Y';
$code = '123456';
// Verify the code
$isValid = $totp->verifyCode($secret, $code);
echo $isValid ? "✅ Code is valid!\n" : "❌ Code is invalid!\n";
```
**输出:**
```
✅ Code is valid!
```
### **生成 QR 码 URI**
```
use RemoteMerge\Totp\TotpFactory;
// Create a new TOTP instance
$totp = TotpFactory::create();
// Example 20-byte Base32 secret and user information
$secret = 'MHYPSU6HI7UUMFTQD24XVUUQR7JLKV6Y';
$uri = $totp->generateUri($secret, 'user@example.com', 'YourApp');
echo "QR Code URI: $uri\n";
```
**输出:**
```
QR Code URI: otpauth://totp/YourApp:user%40example.com?secret=MHYPSU6HI7UUMFTQD24XVUUQR7JLKV6Y&issuer=YourApp&algorithm=SHA1&digits=6&period=30
```
## **自定义选项**
### **更改哈希算法**
默认情况下,TOTP PHP 使用 **SHA1**。该算法可配置为使用 **SHA256** 或 **SHA512**:
```
use RemoteMerge\Totp\TotpFactory;
$totp = TotpFactory::create();
// Configure the algorithm
$totp->configure(['algorithm' => 'SHA256']);
$secret = $totp->generateSecret();
$code = $totp->getCode($secret);
echo "Generated TOTP Code (SHA256): $code\n";
```
### **更改验证码长度**
默认情况下,TOTP PHP 生成 **6 位验证码**。长度可配置为 **8 位**:
```
use RemoteMerge\Totp\TotpFactory;
$totp = TotpFactory::create();
// Configure the code length
$totp->configure(['digits' => 8]);
$secret = $totp->generateSecret();
$code = $totp->getCode($secret);
echo "Generated 8-Digit TOTP Code: $code\n";
```
### **更改时间切片持续时间**
默认情况下,TOTP PHP 使用 **30 秒的时间切片**。持续时间可配置为 **60 秒**:
```
use RemoteMerge\Totp\TotpFactory;
$totp = TotpFactory::create();
// Configure the time slice duration
$totp->configure(['period' => 60]);
$secret = $totp->generateSecret();
$code = $totp->getCode($secret);
echo "Generated TOTP Code (60-second period): $code\n";
```
## **高级用法**
### **带偏差的验证码验证**
通过允许 **±1 个时间切片** 的偏差来处理时钟漂移:
```
use RemoteMerge\Totp\TotpFactory;
$totp = TotpFactory::create();
$secret = 'MHYPSU6HI7UUMFTQD24XVUUQR7JLKV6Y';
$code = '123456';
// Allow discrepancy of 1 time slice
$isValid = $totp->verifyCode($secret, $code, 1);
echo $isValid ? "✅ Code is valid!\n" : "❌ Code is invalid!\n";
```
### **重放攻击防护**
使用 `verifyCodeOnce()` 防止 TOTP 验证码被多次接受。成功时它会返回匹配的时间切片(请存储此值,并在下次登录时将其传回),如果验证码无效或已被使用过,则返回 `null`:
```
use RemoteMerge\Totp\TotpFactory;
$totp = TotpFactory::create();
$secret = 'MHYPSU6HI7UUMFTQD24XVUUQR7JLKV6Y';
$code = '123456';
// Load the last accepted time slice from persistent storage (e.g. database).
// Use 0 on first login.
$lastAcceptedSlice = (int) $user->getLastTotpSlice();
$newSlice = $totp->verifyCodeOnce($secret, $code, $lastAcceptedSlice);
if ($newSlice === null) {
echo "❌ Code is invalid or has already been used!\n";
} else {
// Persist the new slice to block future reuse of this code.
$user->setLastTotpSlice($newSlice);
echo "✅ Code accepted!\n";
}
```
### **密钥安全审计**
在存储或使用密钥之前,使用 `auditSecret()` 对其进行检查。该方法永远不会抛出异常 —— 所有诊断信息都会在结果数组中返回:
```
use RemoteMerge\Totp\TotpFactory;
$totp = TotpFactory::create();
$secret = 'JBSWY3DPEHPK3PXP';
$audit = $totp->auditSecret($secret);
echo "Decoded length: {$audit['length_bytes']} bytes\n";
echo "Strong secret: " . ($audit['is_strong'] ? 'Yes' : 'No') . "\n";
foreach ($audit['warnings'] as $warning) {
echo "⚠️ Warning: $warning\n";
}
```
**输出:**
```
Decoded length: 10 bytes
Strong secret: No
⚠️ Warning: Secret is weak (10 bytes); recommend >= 20 bytes for adequate security.
```
### **配置最大偏差**
默认情况下,`verifyCode()` 和 `verifyCodeOnce()` 中的偏差参数上限为 **10**。在创建实例时传入 `max_discrepancy` 可以收紧或放宽此限制:
```
use RemoteMerge\Totp\TotpFactory;
// Restrict the maximum allowed discrepancy to 2 time slices
$totp = TotpFactory::create(['max_discrepancy' => 2]);
$secret = $totp->generateSecret();
$code = $totp->getCode($secret);
// discrepancy of 1 is within the limit — works normally
$isValid = $totp->verifyCode($secret, $code, 1);
// discrepancy of 3 exceeds the limit — throws TotpException
$totp->verifyCode($secret, $code, 3);
```
### **生成 QR 码图像**
在后端生成 `otpauth://` URI,然后在浏览器中本地渲染 QR 图像。避免将 TOTP 设置 URI 发送给第三方 QR 图像 API,因为该 URI 包含用户的密钥。
```
// secret.php
use RemoteMerge\Totp\TotpFactory;
$totp = TotpFactory::create();
$secret = $totp->generateSecret();
$uri = $totp->generateUri($secret, 'user@example.com', 'YourApp');
echo json_encode([
'secret' => $secret,
'uri' => $uri,
], JSON_THROW_ON_ERROR);
```
```
```
## **使用 Docker 体验**
1. 克隆仓库:
git clone git@github.com:remotemerge/totp-php.git
cd totp-php
2. 启动 Docker 容器:
bash start-docker.sh
3. 通过 `http://localhost:8080` 访问应用。
4. (可选)进入容器 Shell 进行开发:
bash pkg-cli.sh
## **使用 PHP 体验**
1. 克隆仓库:
git clone git@github.com:remotemerge/totp-php.git
cd totp-php
2. 使用 Composer 安装依赖:
composer install
3. 启动 PHP 内置服务器:
php -S localhost:8080 -t public
4. 通过 `http://localhost:8080` 访问应用。
## **获取帮助**
Bug 和功能需求使用 GitHub Issues 进行跟踪,并确定优先级,以确保该库保持可靠和最新。
- **Bug 报告**
可以通过在 GitHub 上[创建 Issue](https://github.com/remotemerge/totp-php/issues/new) 来报告问题。我们会认真处理所有问题,以维护该库的质量。
- **集成协助**
如需集成方面的帮助或对功能有任何疑问,请创建一个 GitHub Issue 或发起讨论。
## **贡献**
- **编码规范**:代码必须遵循 [PER Coding Style 3.0](https://www.php-fig.org/per/coding-style/) 标准。
- **测试**:所有提交的代码必须通过相关测试,以保持该库的可靠性。
- **文档**:规范的文档和清晰的代码实践对于可维护性至关重要。
- **Pull Request**:应向 `main` 分支提交 Pull Request。
我们将审查并感激所有的贡献。
## **项目截图**

标签:ffuf, OpenVAS, PHP, SDK/库, TOTP, 双因素认证, 请求拦截