1. <?php
  2. namespace google;
  3.  
  4. class Goole
  5. {
  6.     protected $_codeLength = 6;
  7.  
  8.     /**
  9.      * Create new secret.
  10.      * 16 characters, randomly chosen from the allowed base32 characters.
  11.      *
  12.      * @param int $secretLength
  13.      *
  14.      * @return string
  15.      */
  16.     public function createSecret($secretLength = 16)
  17.     {
  18.         $validChars = $this->_getBase32LookupTable();
  19.  
  20.         // Valid secret lengths are 80 to 640 bits
  21.         if ($secretLength < 16 || $secretLength > 128) {
  22.             throw new \Exception('Bad secret length');
  23.         }
  24.         $secret = '';
  25.         $rnd = false;
  26.         if (function_exists('random_bytes')) {
  27.             $rnd = random_bytes($secretLength);
  28.         } elseif (function_exists('mcrypt_create_iv')) {
  29.             $rnd = random_bytes($secretLength, MCRYPT_DEV_URANDOM);
  30.         } elseif (function_exists('openssl_random_pseudo_bytes')) {
  31.             $rnd = openssl_random_pseudo_bytes($secretLength, $cryptoStrong);
  32.             if (!$cryptoStrong) {
  33.                 $rnd = false;
  34.             }
  35.         }
  36.         if ($rnd !== false) {
  37.             for ($i = 0; $i < $secretLength; ++$i) {
  38.                 $secret .= $validChars[ord($rnd[$i]) & 31];
  39.             }
  40.         } else {
  41.             throw new \Exception('No source of secure random');
  42.         }
  43.  
  44.         return $secret;
  45.     }
  46.  
  47.     /**
  48.      * Calculate the code, with given secret and point in time.
  49.      *
  50.      * @param string   $secret
  51.      * @param int|null $timeSlice
  52.      *
  53.      * @return string
  54.      */
  55.     public function getCode($secret, $timeSlice = null)
  56.     {
  57.         if ($timeSlice === null) {
  58.             $timeSlice = floor(time() / 30);
  59.         }
  60.  
  61.         $secretkey = $this->_base32Decode($secret);
  62.  
  63.         // Pack time into binary string
  64.         $time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice);
  65.         // Hash it with users secret key
  66.         $hm = hash_hmac('SHA1', $time, $secretkey, true);
  67.         // Use last nipple of result as index/offset
  68.         $offset = ord(substr($hm, -1)) & 0x0F;
  69.         // grab 4 bytes of the result
  70.         $hashpart = substr($hm, $offset, 4);
  71.  
  72.         // Unpak binary value
  73.         $value = unpack('N', $hashpart);
  74.         $value = $value[1];
  75.         // Only 32 bits
  76.         $value = $value & 0x7FFFFFFF;
  77.  
  78.         $modulo = pow(10, $this->_codeLength);
  79.  
  80.         return str_pad($value % $modulo, $this->_codeLength, '0', STR_PAD_LEFT);
  81.     }
  82.  
  83.     /**
  84.      * Get QR-Code URL for image, from google charts.
  85.      *
  86.      * @param string $name
  87.      * @param string $secret
  88.      * @param string $title
  89.      * @param array  $params
  90.      *
  91.      * @return string
  92.      */
  93.     public function getQRCodeGoogleUrl($name, $secret, $title = null, $params = array())
  94.     {
  95.         $width = !empty($params['width']) && (int) $params['width'] > 0 ? (int) $params['width'] : 200;
  96.         $height = !empty($params['height']) && (int) $params['height'] > 0 ? (int) $params['height'] : 200;
  97.         $level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M';
  98.  
  99.         $urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.'');
  100.         if (isset($title)) {
  101.             $urlencoded .= urlencode('&issuer='.urlencode($title));
  102.         }
  103.  
  104.         return 'https://chart.googleapis.com/chart?chs='.$width.'x'.$height.'&chld='.$level.'|0&cht=qr&chl='.$urlencoded.'';
  105.     }
  106.  
  107.     /**
  108.      * Check if the code is correct. This will accept codes starting from $discrepancy*30sec ago to $discrepancy*30sec from now.
  109.      *
  110.      * @param string   $secret
  111.      * @param string   $code
  112.      * @param int      $discrepancy      This is the allowed time drift in 30 second units (8 means 4 minutes before or after)
  113.      * @param int|null $currentTimeSlice time slice if we want use other that time()
  114.      *
  115.      * @return bool
  116.      */
  117.     public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null)
  118.     {
  119.         if ($currentTimeSlice === null) {
  120.             $currentTimeSlice = floor(time() / 30);
  121.         }
  122.  
  123.         if (strlen($code) != 6) {
  124.             return false;
  125.         }
  126.  
  127.         for ($i = -$discrepancy; $i <= $discrepancy; ++$i) {
  128.             $calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
  129.             if ($this->timingSafeEquals($calculatedCode, $code)) {
  130.                 return true;
  131.             }
  132.         }
  133.  
  134.         return false;
  135.     }
  136.  
  137.     /**
  138.      * Set the code length, should be >=6.
  139.      *
  140.      * @param int $length
  141.      *
  142.      * @return PHPGangsta_GoogleAuthenticator
  143.      */
  144.     public function setCodeLength($length)
  145.     {
  146.         $this->_codeLength = $length;
  147.  
  148.         return $this;
  149.     }
  150.  
  151.     /**
  152.      * Helper class to decode base32.
  153.      *
  154.      * @param $secret
  155.      *
  156.      * @return bool|string
  157.      */
  158.     protected function _base32Decode($secret)
  159.     {
  160.         if (empty($secret)) {
  161.             return '';
  162.         }
  163.  
  164.         $base32chars = $this->_getBase32LookupTable();
  165.         $base32charsFlipped = array_flip($base32chars);
  166.  
  167.         $paddingCharCount = substr_count($secret, $base32chars[32]);
  168.         $allowedValues = array(6, 4, 3, 1, 0);
  169.         if (!in_array($paddingCharCount, $allowedValues)) {
  170.             return false;
  171.         }
  172.         for ($i = 0; $i < 4; ++$i) {
  173.             if ($paddingCharCount == $allowedValues[$i] &&
  174.                 substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) {
  175.                 return false;
  176.             }
  177.         }
  178.         $secret = str_replace('=', '', $secret);
  179.         $secret = str_split($secret);
  180.         $binaryString = '';
  181.         for ($i = 0; $i < count($secret); $i = $i + 8) {
  182.             $x = '';
  183.             if (!in_array($secret[$i], $base32chars)) {
  184.                 return false;
  185.             }
  186.             for ($j = 0; $j < 8; ++$j) {
  187.                 $x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
  188.             }
  189.             $eightBits = str_split($x, 8);
  190.             for ($z = 0; $z < count($eightBits); ++$z) {
  191.                 $binaryString .= (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y : '';
  192.             }
  193.         }
  194.  
  195.         return $binaryString;
  196.     }
  197.  
  198.     /**
  199.      * Get array with all 32 characters for decoding from/encoding to base32.
  200.      *
  201.      * @return array
  202.      */
  203.     protected function _getBase32LookupTable()
  204.     {
  205.         return array(
  206.             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //  7
  207.             'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15
  208.             'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23
  209.             'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31
  210.             '=',  // padding char
  211.         );
  212.     }
  213.  
  214.     /**
  215.      * A timing safe equals comparison
  216.      * more info here: http://blog.ircmaxell.com/2014/11/its-all-about-time.html.
  217.      *
  218.      * @param string $safeString The internal (safe) value to be checked
  219.      * @param string $userString The user submitted (unsafe) value
  220.      *
  221.      * @return bool True if the two strings are identical
  222.      */
  223.     private function timingSafeEquals($safeString, $userString)
  224.     {
  225.         if (function_exists('hash_equals')) {
  226.             return hash_equals($safeString, $userString);
  227.         }
  228.         $safeLen = strlen($safeString);
  229.         $userLen = strlen($userString);
  230.  
  231.         if ($userLen != $safeLen) {
  232.             return false;
  233.         }
  234.  
  235.         $result = 0;
  236.  
  237.         for ($i = 0; $i < $userLen; ++$i) {
  238.             $result |= (ord($safeString[$i]) ^ ord($userString[$i]));
  239.         }
  240.  
  241.         // They are only identical strings if $result is exactly 0...
  242.         return $result === 0;
  243.     }
  244. }

使用方法:

  1. $checkResult = $ga->verifyCode($secret, $code, 1);
  2. if ($checkResult) {
  3.     echo '匹配! OK';
  4. } else {
  5.     echo '不匹配! FAILED';
  6. }
  7. ___________________________________相对来说我跟喜欢下面这种用法,实时的
  8. $oneCode = '837476';   //用户输入的
  9. $secre = '4BPFQVCGJGUVQVBL';   //数据库取出来的(用户注册时第一次生成的)
  10. $a = $ga->getCode($secre);
  11. if ($a == $oneCode) {
  12.     return '成功';
  13. } else {
  14.     return '失败';
  15. }
  16. 生成二维码也可以用这个方法
  17. $qrCodeUrl = $ga->getQRCodeGoogleUrl('asdasdas', $secret); 
  18. //第一个参数是"标识",第二个参数为"安全密匙SecretKey" 
  19. 生成二维码信息echo '<img src="'.$qrCodeUrl.'">';

然后下载谷歌验证器绑定key就可以使用

相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!