定制 remotemerge/totp-php 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

remotemerge/totp-php

Composer 安装命令:

composer require remotemerge/totp-php

包简介

Lightweight, fast, and secure TOTP (2FA) authentication library for PHP — battle tested, dependency free, and ready for enterprise integration.

README 文档

README

PHP Version Tests Build Sonar Quality Sonar Coverage Downloads License

TOTP PHP Features

Table of Contents

# Title Description
1 Why TOTP PHP? Ideal for secure logins, data protection, and enhanced user security.
2 Key Features Secure secret generation, multi-algorithm support, QR codes, customization.
3 Compatibility Works seamlessly with all major authenticator apps and RFC-compliant tools.
4 Get Started Quick installation via Composer and simple usage examples.
5 Basic Usage Generate secrets, TOTP codes, verify codes, and create QR code URIs.
6 Customization Change hash algorithms, code length, and time slice duration.
7 Advanced Usage Replay protection, secret auditing, discrepancy limits, and QR codes.
8 Try with Docker Test locally using Docker for quick setup.
9 Try without Docker Use PHP's built-in server for lightweight local testing.
10 Getting Help Report bugs, get integration help, or collaborate on projects.
11 Contribution Follow coding standards, test code, and submit pull requests.
12 Screenshots Visual demo of the library in action.

Why Choose TOTP PHP?

TOTP PHP is a versatile, secure, and reliable TOTP library for PHP that provides easy 2FA integration. This developer-friendly, lightweight, and secure library offers simplicity, performance, and customization for secure login systems, data protection, and enhanced user security. TOTP PHP ensures robust protection with ease of use and high performance, designed for modern PHP developers.

Key Features

Secure Secret Generation Generates cryptographically secure secret keys for TOTP, ensuring maximum security.

Multi Algorithm Support Supports SHA1, SHA256, and SHA512 for HMAC hashing, providing flexibility and compatibility with all major authenticator apps.

QR Code Integration Generates standards-compliant otpauth URIs for QR code setup in authenticator apps like Google Authenticator, Microsoft Authenticator, Authy, and more.

Customizable Code Length Generates TOTP codes with 6 or 8 digits, configurable based on application requirements.

Time Slice Configuration Configurable time slice duration (e.g., 30 or 60 seconds) to match security requirements.

Discrepancy Verification Allows time slice discrepancy when verifying TOTP codes, ensuring a smooth user experience. This is especially useful for handling clock drifts.

Replay Attack Protection The verifyCodeOnce() method prevents reuse of already-accepted codes by tracking the last accepted time slice, eliminating replay attack vectors.

Secret Security Auditing The auditSecret() method inspects a secret key and returns its decoded byte length, strength rating, and actionable warnings — without throwing exceptions.

Discrepancy Bounds Enforcement The discrepancy parameter is validated against a configurable upper bound (default: 10), preventing misconfigured or malicious values from widening the verification window indefinitely.

Easy Verification Verifies TOTP codes with a simple and intuitive API, making integration straightforward.

Lightweight and Fast Built for performance, TOTP PHP is lightweight and optimized for speed, ensuring minimal overhead.

Developer Friendly Designed with developers in mind, TOTP PHP is easy to use, well-documented, and fully tested.

Compatibility

TOTP PHP is built to universal standards and works seamlessly with all major authenticator applications worldwide. Whether users prefer mobile apps, desktop tools, or hardware tokens, this library ensures flawless compatibility across the entire ecosystem.

Supported Authenticator Apps

📱 Mobile Authenticators 💻 Desktop & Hardware
✅ Google Authenticator ✅ YubiKey Authenticator
✅ Microsoft Authenticator ✅ FreeOTP
✅ Authy ✅ OTP Auth (iOS)
✅ Duo Mobile ✅ Aegis Authenticator
✅ 1Password ✅ andOTP
✅ LastPass Authenticator ✅ Any RFC-compliant tool
✅ Bitwarden Authenticator

Standards Compliance

🔒 RFC-Compliant Implementation TOTP PHP follows RFC 6238 for time-based one-time passwords, validates secrets as uppercase RFC 4648 Base32 with valid padding, and generates Key URI Format compatible otpauth:// URIs. The test suite includes the RFC 6238 Appendix B vectors for SHA1, SHA256, and SHA512.

Get Started in Minutes

Adding TOTP PHP to a project is quick and easy. The library requires PHP 8.1 or higher.

Installation

Install the library via Composer:

composer require remotemerge/totp-php

Basic Usage

Generate a Secret Key

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";

Output:

Generated Secret Key: MHYPSU6HI7UUMFTQD24XVUUQR7JLKV6Y

generateSecret() creates a 20-byte random secret encoded as uppercase Base32. When importing secrets from another system, use auditSecret() to inspect decoded length and formatting before storing them.

Generate a TOTP Code

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";

Output:

Generated TOTP Code: 123456

Verify a TOTP Code

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";

Output:

✅ Code is valid!

Generate a QR Code 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";

Output:

QR Code URI: otpauth://totp/YourApp:user%40example.com?secret=MHYPSU6HI7UUMFTQD24XVUUQR7JLKV6Y&issuer=YourApp&algorithm=SHA1&digits=6&period=30

Customization Options

Change the Hash Algorithm

By default, TOTP PHP uses SHA1. The algorithm can be configured to use SHA256 or 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";

Change the Code Length

By default, TOTP PHP generates 6-digit codes. The length can be configured to 8 digits:

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";

Change the Time Slice Duration

By default, TOTP PHP uses a 30-second time slice. The duration can be configured to 60 seconds:

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";

Advanced Usage

Verify Code with Discrepancy

Handle clock drift by allowing a discrepancy of ±1 time slice:

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";

Replay Attack Protection

Use verifyCodeOnce() to prevent a TOTP code from being accepted more than once. It returns the matched time slice on success (store this value and pass it back on the next login), or null if the code is invalid or has already been used:

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";
}

Secret Security Audit

Use auditSecret() to inspect a secret key before storing or using it. The method never throws — all diagnostics are returned in the result array:

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";
}

Output:

Decoded length: 10 bytes
Strong secret: No
⚠️  Warning: Secret is weak (10 bytes); recommend >= 20 bytes for adequate security.

Configuring the Maximum Discrepancy

By default the discrepancy parameter in verifyCode() and verifyCodeOnce() is capped at 10. Pass max_discrepancy when creating the instance to tighten or relax this limit:

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);

Generate a QR Code Image

Generate the otpauth:// URI on the backend, then render the QR image locally in the browser. Avoid sending TOTP setup URIs to third-party QR image APIs because the URI contains the user's secret.

// 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);
<img id="qrImage" src="" alt="Authenticator QR code">

<script type="module">
  import QRCode from 'https://cdn.jsdelivr.net/npm/qrcode@1.5/+esm';

  const response = await fetch('/secret.php');
  const data = await response.json();

  document.getElementById('qrImage').src = await QRCode.toDataURL(data.uri, {
    errorCorrectionLevel: 'H',
    width: 256,
    margin: 2,
  });
</script>

Try with Docker

Test the TOTP PHP library locally using Docker. This method automatically sets up the environment with all dependencies. Follow these steps:

  1. Clone the repository:

    git clone git@github.com:remotemerge/totp-php.git
    cd totp-php
  2. Start the Docker container:

    bash start-docker.sh
  3. Access the application at http://localhost:8080.

  4. (Optional) Access the container shell for development:

    bash pkg-cli.sh

Try with PHP

For a lightweight setup, use PHP's built-in server. This method is ideal for quick local testing and doesn't require Docker. Follow these steps:

  1. Clone the repository:

    git clone git@github.com:remotemerge/totp-php.git
    cd totp-php
  2. Install dependencies using Composer:

    composer install
  3. Start the PHP built-in server:

    php -S localhost:8080 -t public
  4. Access the application at http://localhost:8080.

Getting Help

Bugs and feature requests are tracked using GitHub issues and prioritized to ensure the library remains reliable and up to date.

  • Bug Reports Issues can be reported by opening an issue on GitHub. All issues are addressed diligently to maintain the library's quality.

  • Integration Assistance For assistance with integration or questions about features, please open a GitHub issue or discussion.

Contribution

Contributions from the Open Source community are highly valued and appreciated. To ensure a smooth and efficient process, contributors should adhere to the following guidelines:

  • Coding Standards: Code must adhere to PER Coding Style 3.0 standards.
  • Testing: All submitted code must pass relevant tests to maintain the library's reliability.
  • Documentation: Proper documentation and clean code practices are essential for maintainability.
  • Pull Requests: Pull requests should be made to the main branch.

All contributions are reviewed and appreciated.

Screenshots

Screenshot 1

remotemerge/totp-php 适用场景与选型建议

remotemerge/totp-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 18.09k 次下载、GitHub Stars 达 21, 最近一次更新时间为 2024 年 12 月 28 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「security」 「Authentication」 「auth」 「two-factor」 「otp」 「totp」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 remotemerge/totp-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 remotemerge/totp-php 我们能提供哪些服务?
定制开发 / 二次开发

基于 remotemerge/totp-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 18.09k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 21
  • 点击次数: 38
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 21
  • Watchers: 2
  • Forks: 4
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-12-28