Google Authenticator丹锹,是谷歌推出的一款動態(tài)口令工具,解決大家的google賬戶遭到惡意攻擊的問題馏谨;許多安全性比較高的網(wǎng)站都會采用這種工具來驗證登錄或者交易别渔;這個動態(tài)口令就是Google身份驗證器每隔30s會動態(tài)生成一個6位數(shù)的數(shù)字。它的作用是:對你的賬號進行“二步驗證”保護惧互,或者說做一個雙重身份驗證哎媚,來達到提升安全級別的目的。
通過 一致算法保持手機端和服務端相同喊儡,并每30秒改變認證碼拨与。
一致算法:
totp是基于時間的,htop是基于次數(shù)的艾猜。
秘鑰生成原理(基于時間)
1买喧、時間戳捻悯,精確到微秒,除以1000淤毛,除以30(動態(tài)6位數(shù)字每30秒變化一次)
2今缚、對時間戳余數(shù) hmac_sha1 編碼
3、然后 base32 encode 標準編碼
4低淡、輸出大寫字符串姓言,即秘鑰
動態(tài)6位數(shù)字驗證:
Google Authenticator會基于密鑰和時間計算一個HMAC-SHA1的hash值,這個hash是160 bit的蔗蹋,然后將這個hash值隨機取連續(xù)的4個字節(jié)生成32位整數(shù)何荚,最后將整數(shù)取31位,再取模得到一個的整數(shù)纸颜。
這個就是Google Authenticator顯示的數(shù)字兽泣。
在服務器端驗證的時候,同樣的方法來計算出數(shù)字胁孙,然后比較計算出來的結(jié)果和用戶輸入的是否一致唠倦。
Google Authenticator PHP類
https://github.com/PHPGangsta/GoogleAuthenticator
生成安全碼并綁定手機
<?php
require_once './PHPGangsta/GoogleAuthenticator.php';
$ga = new PHPGangsta_GoogleAuthenticator();
// 創(chuàng)建新的"安全密匙SecretKey"
// 把本次的"安全密匙SecretKey" 入庫,和賬戶關(guān)系綁定,客戶端也是綁定這同一個"安全密匙SecretKey"
// 安全密匙SecretKey 可以和手機端綁定
$secret = $ga->createSecret();
echo "安全密匙SecretKey: " . $secret . "\n\n";
//第一個參數(shù)是"標識",第二個參數(shù)為"安全密匙SecretKey" 生成二維碼信息
$qrCodeUrl = $ga->getQRCodeGoogleUrl('www.xxx.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.xxx.com%3Fsecret%3DM5X3M4PGBQRFPUTY&size=200x200&ecc=M
綁定手機方式
- 通過安全秘鑰
-
通過二維碼(圖片地址就是Google Charts生成的可以直接打開)
image.png
動態(tài)口令驗證
<?php
require_once './PHPGangsta/GoogleAuthenticator.php';
$ga = new PHPGangsta_GoogleAuthenticator();
// 把提交的驗證碼和服務端上生成的驗證碼做對比
// $secret 服務端的 "安全密匙SecretKey"
// $oneCode 手機上看到的 "一次性驗證碼"
// 最后一個參數(shù) 為容差時間,這里是2 那么就是 2* 30 sec 一分鐘.
$oneCode = '371922';
$secret = 'M5X3M4PGBQRFPUTY';
$checkResult = $ga->verifyCode($secret, $oneCode, 2);
if ($checkResult) {
//這里添加自定義邏輯
echo '匹配! OK';
} else {
echo '匹配! FAILED';
}