rikudou / google-authenticator
兼容Google Authenticator的简单OTP生成器
v1.0
2018-02-28 14:17 UTC
Requires
- christian-riesen/base32: ^1.3
This package is auto-updated.
Last update: 2024-09-07 03:44:46 UTC
README
非常简单,可以集成到几乎所有东西中。
安装
在composer依赖中包含 rikudou/google-authenticator
,例如:composer require rikudou/google-authenticator
。
使用方法
<?php use rikudou\GoogleAuthenticator\Authenticator; // create a secret key, you can than store it in db or whatever $secretKey = Authenticator::generateSecret(); // holds something like 4O7LDGME6HHINEP7 // get otp code $authenticator = new Authenticator($secretKey); $otpCode = $authenticator->getCode(); // holds a string with six digits number, e.g. 408532 // verify submitted code $userSubmittedCode = $_POST['2facode']; // just an example, get the code however you want $isCorrect = $authenticator->verify($userSubmittedCode); // holds true or false
就是这样,很简单。
处理异常
有两种情况下可能会抛出异常。
<?php use rikudou\GoogleAuthenticator\Authenticator; use rikudou\GoogleAuthenticator\AuthenticatorException; try { $secret = Authenticator::generateSecret(200); } catch (AuthenticatorException $exception) { switch ($exception->getCode()) { case AuthenticatorException::INVALID_SECRET_LENGTH: // Exception message: "Could not create secret, length invalid. Valid value is an integer between 16 and 128, 200 given" break; case AuthenticatorException::NO_RANDOMNESS_SOURCE: // Exception message: "No randomness source for 'random_int()' found" // This should not happen on any modern system break; } }
就这样,大家!