php通过谷歌身份验证实现动态口令

Google Authenticator PHP类

https://github.com/PHPGangsta/GoogleAuthenticator

生成安全码并绑定手机

<?php
​
require_once './PHPGangsta/GoogleAuthenticator.php';
​
$ga = new PHPGangsta_GoogleAuthenticator();
​
// 创建新的"安全密匙SecretKey"
// 把本次的"安全密匙SecretKey" 入库,和账户关系绑定,客户端也是绑定这同一个"安全密匙SecretKey"
// 安全密匙SecretKey 可以和手机端绑定
$secret = $ga->createSecret();
​
echo "安全密匙SecretKey: " . $secret . "\n\n";
​
//第一个参数是"标识",第二个参数为"安全密匙SecretKey" 生成二维码信息
$qrCodeUrl = $ga->getQRCodeGoogleUrl('www.yundou.com', $secret);
​
//Google Charts接口 生成的二维码图片,方便手机端扫描绑定安全密匙SecretKey
echo "Google Charts URL for the QR-Code: " . $qrCodeUrl . "\n\n";
​

输出:

安全密匙SecretKey: M5X3M4PGBQRFPUTY
​
Google Charts URL for the QR-Code: https://api.qrserver.com/v1/create-qr-code/?data=otpauth%3A%2F%2Ftotp%2Fwww.yundou.com%3Fsecret%3DM5X3M4PGBQRFPUTY&size=200x200&ecc=M
​

绑定手机方式(可以使用谷歌身份验证器或者FreeOTP)

  • 通过安全秘钥
  • 通过二维码(图片地址就是Google Charts生成的可以直接打开)

生成二维码样例地址(二维码是不让发):

http://p1.toutiaoimg.com/large/pgc-image/bade464f1a854a939344be12aa2aab79

动态口令验证

<?php
​
require_once './PHPGangsta/GoogleAuthenticator.php';
​
$ga = new PHPGangsta_GoogleAuthenticator();
​
// 把提交的验证码和服务端上生成的验证码做对比
// $secret 服务端的 "安全密匙SecretKey"
// $oneCode 手机上看到的 "一次性验证码"
// 最后一个参数 为容差时间,这里是2 那么就是 2* 30 sec 一分钟.
$oneCode = '371922';
$secret = 'M5X3M4PGBQRFPUTY';
​
$checkResult = $ga->verifyCode($secret, $oneCode, 2);
​
​
if ($checkResult) {
 //这里添加自定义逻辑
 echo '匹配! OK';
} else {
 echo '匹配! FAILED';
}
​

https://github.com/PHPGangsta/GoogleAuthenticator

举报
评论 0