<?php

/**
* PHP Class for handling Google Authenticator 2-factor authentication
*
* @author Michael Kliewe
* @copyright 2012 Michael Kliewe
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://www.phpgangsta.de/
*/ class PHPGangsta_GoogleAuthenticator
{
protected $_codeLength = 6; /**
* Create new secret.
* 16 characters, randomly chosen from the allowed base32 characters.
*
* @param int $secretLength
* @return string
*/
public function createSecret($secretLength = 16)
{
$validChars = $this->_getBase32LookupTable();
unset($validChars[32]); $secret = '';
for ($i = 0; $i < $secretLength; $i++) {
$secret .= $validChars[array_rand($validChars)];
}
return $secret;
} /**
* Calculate the code, with given secret and point in time
*
* @param string $secret
* @param int|null $timeSlice
* @return string
*/
public function getCode($secret, $timeSlice = null)
{
if ($timeSlice === null) {
$timeSlice = floor(time() / 30);
} $secretkey = $this->_base32Decode($secret); // Pack time into binary string
$time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice);
// Hash it with users secret key
$hm = hash_hmac('SHA1', $time, $secretkey, true);
// Use last nipple of result as index/offset
$offset = ord(substr($hm, -1)) & 0x0F;
// grab 4 bytes of the result
$hashpart = substr($hm, $offset, 4); // Unpak binary value
$value = unpack('N', $hashpart);
$value = $value[1];
// Only 32 bits
$value = $value & 0x7FFFFFFF; $modulo = pow(10, $this->_codeLength);
return str_pad($value % $modulo, $this->_codeLength, '0', STR_PAD_LEFT);
} /**
* Get QR-Code URL for image, from google charts
*
* @param string $name
* @param string $secret
* @return string
*/
public function getQRCodeGoogleUrl($name, $secret) {
$urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.'');
return 'https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl='.$urlencoded.'';
} /**
* Check if the code is correct. This will accept codes starting from $discrepancy*30sec ago to $discrepancy*30sec from now
*
* @param string $secret
* @param string $code
* @param int $discrepancy This is the allowed time drift in 30 second units (8 means 4 minutes before or after)
* @return bool
*/
public function verifyCode($secret, $code, $discrepancy = 1)
{
$currentTimeSlice = floor(time() / 30); for ($i = -$discrepancy; $i <= $discrepancy; $i++) {
$calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
if ($calculatedCode == $code ) {
return true;
}
} return false;
} /**
* Set the code length, should be >=6
*
* @param int $length
* @return PHPGangsta_GoogleAuthenticator
*/
public function setCodeLength($length)
{
$this->_codeLength = $length;
return $this;
} /**
* Helper class to decode base32
*
* @param $secret
* @return bool|string
*/
protected function _base32Decode($secret)
{
if (empty($secret)) return ''; $base32chars = $this->_getBase32LookupTable();
$base32charsFlipped = array_flip($base32chars); $paddingCharCount = substr_count($secret, $base32chars[32]);
$allowedValues = array(6, 4, 3, 1, 0);
if (!in_array($paddingCharCount, $allowedValues)) return false;
for ($i = 0; $i < 4; $i++){
if ($paddingCharCount == $allowedValues[$i] &&
substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) return false;
}
$secret = str_replace('=','', $secret);
$secret = str_split($secret);
$binaryString = "";
for ($i = 0; $i < count($secret); $i = $i+8) {
$x = "";
if (!in_array($secret[$i], $base32chars)) return false;
for ($j = 0; $j < 8; $j++) {
$x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
}
$eightBits = str_split($x, 8);
for ($z = 0; $z < count($eightBits); $z++) {
$binaryString .= ( ($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48 ) ? $y:"";
}
}
return $binaryString;
} /**
* Helper class to encode base32
*
* @param string $secret
* @param bool $padding
* @return string
*/
protected function _base32Encode($secret, $padding = true)
{
if (empty($secret)) return ''; $base32chars = $this->_getBase32LookupTable(); $secret = str_split($secret);
$binaryString = "";
for ($i = 0; $i < count($secret); $i++) {
$binaryString .= str_pad(base_convert(ord($secret[$i]), 10, 2), 8, '0', STR_PAD_LEFT);
}
$fiveBitBinaryArray = str_split($binaryString, 5);
$base32 = "";
$i = 0;
while ($i < count($fiveBitBinaryArray)) {
$base32 .= $base32chars[base_convert(str_pad($fiveBitBinaryArray[$i], 5, '0'), 2, 10)];
$i++;
}
if ($padding && ($x = strlen($binaryString) % 40) != 0) {
if ($x == 8) $base32 .= str_repeat($base32chars[32], 6);
elseif ($x == 16) $base32 .= str_repeat($base32chars[32], 4);
elseif ($x == 24) $base32 .= str_repeat($base32chars[32], 3);
elseif ($x == 32) $base32 .= $base32chars[32];
}
return $base32;
} /**
* Get array with all 32 characters for decoding from/encoding to base32
*
* @return array
*/
protected function _getBase32LookupTable()
{
return array(
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', //
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', //
'Y', 'Z', '2', '3', '4', '5', '6', '7', //
'=' // padding char
);
}
}

调用代码

<?php

require_once '../PHPGangsta/GoogleAuthenticator.php';

$ga = new PHPGangsta_GoogleAuthenticator();

$secret = 'WB4NO2VHPC6WX57O';//$ga->createSecret();
echo "Secret is: ".$secret."\n\n";
echo '<br/>';
$qrCodeUrl = $ga->getQRCodeGoogleUrl('cxsoft', $secret);
echo "Google Charts URL for the QR-Code: ".$qrCodeUrl."\n\n";
echo '<br>'; $oneCode = '651595';//$ga->getCode($secret);
echo "Checking Code '$oneCode' and Secret '$secret':\n";
echo '<br>';
$checkResult = $ga->verifyCode($secret, $oneCode, 1); // 1 = 1*30sec clock tolerance
if ($checkResult) {
echo 'OK';
} else {
echo 'FAILED';
}

GoogleAuthenticator的更多相关文章

  1. FreeRadius+GoogleAuthenticator实现linux动态口令认证

    简介 在运维管理中,服务器的密码管理十分重要.服务器数量少的时候还好说,可以定时来改密码.一旦数量多了,再来改密码就不现实了. 前提 我们假定运维访问服务器是这样的: 创建一个普通用户用于登录服务器, ...

  2. 使用Google-Authenticator加强serverSSH登录

    对于须要特殊加密的人群,我这里给出对应的方法来进行谷歌式加密. 过程例如以下: 准备: 首先在你的手机上准备好client(自己百度下载) 接下来依照命令做: date 查看系统时间       da ...

  3. 堡垒机安装google-authenticator

    公司线上的使用机器不能让用户随意的登陆,所以就不能让开发随意的登陆到生产的机器的.于是就打算使用google-auth的验证方式呢. 如果google-auth的方式. 搭建google-authen ...

  4. c#使用谷歌身份验证GoogleAuthenticator

    此功能相当于给系统加了个令牌,只有输入对的一组数字才可以验证成功.类似于QQ令牌一样. 一丶创建最核心的一个类GoogleAuthenticator 此类包含了生成密钥,验证,将绑定密钥转为二维码. ...

  5. Linux 利用Google Authenticator实现ssh登录双因素认证

    1.介绍 双因素认证:双因素身份认证就是通过你所知道再加上你所能拥有的这二个要素组合到一起才能发挥作用的身份认证系统.双因素认证是一种采用时间同步技术的系统,采用了基于时间.事件和密钥三变量而产生的一 ...

  6. linux上使用google身份验证器(简版)

    系统:centos6.6 下载google身份验证包google-authenticator-master(其实只是一个.zip文件,在windwos下解压,然后传进linux) #cd /data/ ...

  7. Java工程师成神之路

    学习Java的同学注意了!!! 学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入Java学习交流群,群号码:279558494 我们一起学Java! 一.基础篇 1.1 JVM 1.1.1. J ...

  8. Linux服务器安全登录设置记录

    在日常运维工作中,对加固服务器的安全设置是一个机器重要的环境.比较推荐的做法是:1)严格限制ssh登陆(参考:Linux系统下的ssh使用(依据个人经验总结)):     修改ssh默认监听端口    ...

  9. 动态令牌-(OTP,HOTP,TOTP)-基本原理

    名词解释和基本介绍 OTP 是 One-Time Password的简写,表示一次性密码. HOTP 是HMAC-based One-Time Password的简写,表示基于HMAC算法加密的一次性 ...

随机推荐

  1. C语言结构体的对齐原则

    Q:关于结构体的对齐,到底遵循什么原则?A:首先先不讨论结构体按多少字节对齐,先看看只以1字节对齐的情况: #include <stdio.h> #include <string.h ...

  2. Windows窗口样式速查参考,Delphi窗口控件的风格都有它们来决定(附Delphi何时用到它们,并举例说明)good

    /* 窗口样式参考列表(都是GetWindowLong的GWL_STYLE风格,都是TCreateParams.Sytle的一部分),详细列表如下:https://msdn.microsoft.com ...

  3. Tomcat默认打开项目设置

    Tomcat设置默认启动项目 Tomcat设置默认启动项目,顾名思义,就是让可以在浏览器的地址栏中输入ip:8080,就能访问到我们的项目.具体操作如下: 1.打开tomcat的安装根目录,找到Tom ...

  4. PHP SSL Module "subjectAltNames"空字节处理安全绕过漏洞

    漏洞版本: PHP 5.3.27 PHP 5.4.17 PHP 5.5.1 漏洞描述: Bugtraq ID:61776 PHP是一种HTML内嵌式的脚本语言 PHP SSL模块不正确处理服务器SSL ...

  5. Linux Shell编程(11)——退出和退出状态

    exit命令一般用于结束一个脚本,就像C语言的exit一样.它也能返回一个值给父进程.每一个命令都能返回一个退出状态(有时也看做返回状态).一个命令执行成功返回0,一个执行不成功的命令则返回一个非零值 ...

  6. JavaScript高级程序设计15.pdf

    组合继承的问题是会调用2次超类型构造函数 寄生组合式继承 即通过借用构造函数来继承属性,通过原型链的形式来继承方法,思路:不必为了指定子类型的原型而调用超类型的原型,我们所需要的无非是超类型原型的一个 ...

  7. Bzoj 2718: [Violet 4]毕业旅行 && Bzoj 1143: [CTSC2008]祭祀river 传递闭包,二分图匹配,匈牙利,bitset

    1143: [CTSC2008]祭祀river Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 1878  Solved: 937[Submit][St ...

  8. CSS3 概览 更新时间 2014-0412-1317

    CSS3 概览 CSS3可以划分为:文字.边框模型.背景.动画等. CSS3颜色模块 CSS2.1的时候可以使用4种颜色方式,直接使用颜色名,如 redRGB值,如 rgb(0,90,255)RGB百 ...

  9. [LeetCode] Word Break 解题思路

    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...

  10. Google网页搜索

    本博文的主要内容有 .Google网页搜索的介绍 .Google网页搜索的使用偏好设置 .Google网页搜索的普通搜索 .Google网页搜索的高级搜索 .Google高级搜索之一:布尔逻辑搜索   ...