xp-forge/google-authenticator

谷歌身份验证器(HOTP & TOTP)

v5.2.0 2024-03-24 10:38 UTC

This package is auto-updated.

Last update: 2024-08-24 11:26:07 UTC


README

Build status on GitHub XP Framework Module BSD Licence Requires PHP 7.0+ Supports PHP 8.0+ Latest Stable Version

支持根据 RFC 4226RFC 6238 标准实现的单次密码(HOTP & TOTP)。

使用一次性密码

以下展示了基于时间的一次性密码(TOTP)的API

use com\google\authenticator\{TimeBased, Tolerance};
use util\Secret;

$secret= new Secret('2BX6RYQ4MD5M46KP');
$timebased= new TimeBased($secret);
$time= time();

// Get token for a given time
$token= $timebased->at($time);
$token= $timebased->current();

// Must match exactly
$verified= $timebased->verify($token, $time, Tolerance::$NONE);

// Allows previous and next
$verified= $timebased->verify($token);
$verified= $timebased->verify($token, $time);
$verified= $timebased->verify($token, $time, Tolerance::$PREVIOUS_AND_NEXT);

以下展示了基于计数器的一次性密码(HOTP)的API

use com\google\authenticator\{CounterBased, Tolerance};
use util\Secret;

$secret= new Secret('2BX6RYQ4MD5M46KP');
$counterbased= new CounterBased($secret);
$counter= 0;

// Get token for a given counter
$token= $counterbased->at($counter);

// Must match exactly
$verified= $counterbased->verify($token, $counter, Tolerance::$NONE);

// Allows previous and next
$verified= $counterbased->verify($token, $counter);
$verified= $counterbased->verify($token, $counter, Tolerance::$PREVIOUS_AND_NEXT);

注意:我们使用 util.Secret,以确保在发生异常时,密钥不会出现在堆栈跟踪中。

创建密钥

作为OTP的发行者,您需要创建随机密钥以初始化客户端和服务器。通过使用 provisioningUri() 方法,您可以获取配置客户端所用的URI。

use com\google\authenticator\{CounterBased, TimeBased, Secrets};

$random= Secrets::random();

// HOTP, otpauth://hotp/{account}?secret={secret}&counter={counter}
$counterbased= new CounterBased($random);
$uri= $counterbased->provisioningUri($account);             // Start with counter= 0
$uri= $counterbased->provisioningUri($account, $initial);   // Start with counter= $initial

// TOTP, otpauth://totp/{account}?secret={secret}
$timebased= new TimeBased($random);
$uri= $timebased->provisioningUri($account);

// Pass a map of string to append additional parameters
$uri= $timebased->provisioningUri($account, ['issuer' => 'ACME Co']);

// Pass an array to namespace the account, yields "ACME%20Co:user@example.com"
$uri= $timebased->provisioningUri(['ACME Co', 'user@example.com']);