lfkeitel/phptotp

PHP 的 TOTP/HOTP 库

v1.1.0 2022-04-07 20:52 UTC

This package is auto-updated.

Last update: 2024-09-08 01:52:40 UTC


README

这是一个简单的 PHP 库和脚本,可以生成 HOTP 和 TOTP 令牌。库完全符合 RFC 4226 和 RFC 6238。支持所有哈希算法,以及令牌长度和 TOTP 的起始时间。

安装

将以下内容添加到您的 composer.json 文件中

{
    "require": {
        "lfkeitel/phptotp": "^1.0"
    }
}

然后运行 composer install

使用

<?php

use lfkeitel\phptotp\{Base32,Totp};

# Generate a new secret key
# Note: GenerateSecret returns a string of random bytes. It must be base32 encoded before displaying to the user. You should store the unencoded string for later use.
$secret = Totp::GenerateSecret(16);

# Display new key to user so they can enter it in Google Authenticator or Authy
echo Base32::encode($secret);

# Generate the current TOTP key
# Note: GenerateToken takes a base32 decoded string of bytes.
$key = (new Totp())->GenerateToken($secret);

# Check if user submitted correct key
if ($user_submitted_key !== $key) {
    exit();
}

文档

lfkeitel\phptotp\Totp 扩展 Hotp

  • __construct($algo = 'sha1', $start = 0, $ti = 30): Totp
    • $algo: 生成令牌时使用的算法
    • $start: 时间的开始
    • $ti: 令牌之间的时间间隔
  • GenerateToken($key, $time = null, $length = 6): string
    • $key: 作为字节,base32 解码的密钥
    • $time: 用于令牌的时间,默认为当前时间
    • $length: 令牌长度

lfkeitel\phptotp\Hotp

  • __construct($algo = 'sha1'): Hotp
    • $algo: 生成令牌时使用的算法
  • GenerateToken($key, $count = 0, $length = 6): string
    • $key: 作为字节,base32 解码的密钥
    • $count: HOTP 计数器
    • $length: 令牌长度
  • GenerateSecret($length = 16): string
    • $length: 字节字符串的长度
    • 返回值:此方法返回一个随机字节字符串,当向用户显示时使用 Base32::encode。

lfkeitel\phptotp\Base32

  • static encode($data): string
    • $data: 要 base32 编码的数据
  • static decode($data): string
    • $data: 要 base32 解码的数据

generate.php

generate.php 是一个脚本,其行为与 Google Authenticator 完全相同。它接受一个密钥,可以是参数,也可以在提示时输入标准输入。假设使用 SHA1、Unix 时间戳作为起始时间和 30 秒的时间间隔生成令牌。密钥应该是 base32 编码的。

$ ./generate.php
Enter secret key: turtles
Token: 338914
$

许可证

此软件根据 MIT 许可证发布,许可证可在 LICENSE 文件中找到。