当前位置: 首页 > 编程文章 >

ThinkPHP 3.2.3 集成 Google Authenticator 动态口令认证方案

ThinkPHP 3.2.3 集成 Google Authenticator 动态口令认证方案

作者:许宁时间:2026-07-12 12:51:48浏览:511

针对静态密码易被窃取的安全隐患,本文介绍在 ThinkPHP 3.2.3 框架中集成基于时间计数的 TOTP(RFC6238)动态口令认证方案。通过封装 OATH 算法与 Base32 编码类,结合 Google Authenticator 生成二维码及验证逻辑,实现用户从静态密码向双因素认证的平滑过渡,提升系统登录安全性。

本文目录展开

动态口令认证背景与方案选型

当前多数系统依赖静态密码进行身份认证,然而静态密码极易遭受窃取,其安全强度已难以满足现代安全需求。

动态口令机制通过“一次一密”及“即时作废”策略,有效阻断了因密码泄露导致的安全风险。常见的动态口令标准包括 HOTP(基于事件计数,遵循 RFC4226)、TOTP(基于时间计数,遵循 RFC6238)以及 OCRA(挑战应答式,遵循 RFC6287)。

本方案重点阐述如何集成 TOTP 方式的动态口令认证。开发环境选用 ThinkPHP 3.2.3 框架,并采用 Google Authenticator 作为动态口令生成与校验的核心组件。

第一步:为 ThinkPHP 框架引入 OATH 算法类库。

OATH 算法的封装类 oath.php 核心代码如下:


<?PHP
/**
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * PHP Google two-factor authentication module.
 *
 * See http://www.idontplaydarts.com/2011/07/google-totp-two-factor-authentication-for-php/
 * for more details
 *
 * @author Phil
 **/

class Google2FA {

 const keyRegeneration  = 30; // Interval between key regeneration
 const otpLength  = 6; // Length of the Token generated

 private static $lut = array( // Lookup needed for Base32 encoding
  "A" => 0, "B" => 1,
  "C" => 2, "D" => 3,
  "E" => 4, "F" => 5,
  "G" => 6, "H" => 7,
  "I" => 8, "J" => 9,
  "K" => 10, "L" => 11,
  "M" => 12, "N" => 13,
  "O" => 14, "P" => 15,
  "Q" => 16, "R" => 17,
  "S" => 18, "T" => 19,
  "U" => 20, "V" => 21,
  "W" => 22, "X" => 23,
  "Y" => 24, "Z" => 25,
  "2" => 26, "3" => 27,
  "4" => 28, "5" => 29,
  "6" => 30, "7" => 31
 );

 /**
  * Generates a 16 digit secret key in base32 format
  * @return string
  **/
 public static function generate_secret_key($length = 16) {
  $b32  = "234567QWERTYUIOPASDFGHJKLZXCVBNM";
  $s  = "";

  for ($i = 0; $i < $length; $i++)
   $s .= $b32[rand(0,31)];

  return $s;
 }

 /**
  * Returns the current Unix Timestamp devided by the keyRegeneration
  * period.
  * @return integer
  **/
 public static function get_timestamp() {
  return floor(microtime(true)/self::keyRegeneration);
 }

 /**
  * Decodes a base32 string into a binary string.
  **/
 public static function base32_decode($b32) {

  $b32  = strtoupper($b32);

  if (!preg_match('/^[ABCDEFGHIJKLMNOPQRSTUVWXYZ234567]+$/', $b32, $match))
   throw new Exception('Invalid characters in the base32 string.');

  $l  = strlen($b32);
  $n = 0;
  $j = 0;
  $binary = "";

  for ($i = 0; $i < $l; $i++) {

   $n = $n << 5;     // Move buffer left by 5 to make room
   $n = $n + self::$lut[$b32[$i]];  // Add value into buffer
   $j = $j + 5;    // Keep track of number of bits in buffer

   if ($j >= 8) {
    $j = $j - 8;
    $binary .= chr(($n & (0xFF << $j)) >> $j);
   }
  }

  return $binary;
 }
 /*by tang*/  
 public static function base32_encode($data, $length){
  $basestr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
  $count = 0;
  if ($length > 0) {
   $buffer = $data[0];
   $next = 1;
   $bitsLeft = 8;

   while (($bitsLeft > 0 || $next < $length)) {
    if ($bitsLeft < 5) {
    if ($next < $length) {
     $buffer <<= 8;
     $buffer |= $data[$next++] & 0xFF;
     $bitsLeft += 8;
    } else {
     $pad = 5 - $bitsLeft;
     $buffer <<= $pad;
     $bitsLeft += $pad;
    }
    }
    $index = 0x1F & ($buffer >> ($bitsLeft - 5));
    $bitsLeft -= 5;
    $result .= $basestr[$index];
    $count++;
   }
   }
   return $result;  
 }
 /**
  * Takes the secret key and the timestamp and returns the one time
  * password.
  *
  * @param binary $key - Secret key in binary form.
  * @param integer $counter - Timestamp as returned by get_timestamp.
  * @return string
  **/
 public static function oath_hotp($key, $counter)
 {
  if (strlen($key) < 8)
  throw new Exception('Secret key is too short. Must be at least 16 base 32 characters');

  $bin_counter = pack('N*', 0) . pack('N*', $counter);  // Counter must be 64-bit int
  $hash  = hash_hmac ('sha1', $bin_counter, $key, true);

  return str_pad(self::oath_truncate($hash), self::otpLength, '0', STR_PAD_LEFT);
 }

 /**
  * Verifys a user inputted key against the current timestamp. Checks $window
  * keys either side of the timestamp.
  *
  * @param string $b32seed
  * @param string $key - User specified key
  * @param integer $window
  * @param boolean $useTimeStamp
  * @return boolean
  **/
 public static function verify_key($b32seed, $key, $window = 5, $useTimeStamp = true) {

  $timeStamp = self::get_timestamp();

  if ($useTimeStamp !== true) $timeStamp = (int)$useTimeStamp;

  $binarySeed = self::base32_decode($b32seed);

  for ($ts = $timeStamp - $window; $ts <= $timeStamp + $window; $ts++)
   if (self::oath_hotp($binarySeed, $ts) == $key)
    return true;

  return false;

 }

 /**
  * Extracts the OTP from the SHA1 hash.
  * @param binary $hash
  * @return integer
  **/
 public static function oath_truncate($hash)
 {
  $offset = ord($hash[19]) & 0xf;

  return (
   ((ord($hash[$offset+0]) & 0x7f) << 24 ) |
   ((ord($hash[$offset+1]) & 0xff) << 16 ) |
   ((ord($hash[$offset+2]) & 0xff) << 8 ) |
   (ord($hash[$offset+3]) & 0xff)
  ) % pow(10, self::otpLength);
 }


}
/*
$InitalizationKey = "LFLFMU2SGVCUIUCZKBMEKRKLIQ";     // Set the inital key

$TimeStamp  = Google2FA::get_timestamp();
$secretkey  = Google2FA::base32_decode($InitalizationKey); // Decode it into binary
$otp    = Google2FA::oath_hotp($secretkey, $TimeStamp); // Get current token

echo("Init key: $InitalizationKey\n");
echo("Timestamp: $TimeStamp\n");
echo("One time password: $otp\n");

// Use this to verify a key as it allows for some time drift.

$result = Google2FA::verify_key($InitalizationKey, "123456");

var_dump($result);
*/
?>

鉴于 Google 动态口令算法中的种子密钥采用 Base32 编码格式,因此必须配套实现 Base32 编解码功能。base32.php 的具体内容如下:


<?php
//namespace Base32;
/**
 * Base32 encoder and decoder
 *
 * Last update: 2012-06-20
 *
 * RFC 4648 compliant
 * @link http://www.ietf.org/rfc/rfc4648.txt
 *
 * Some groundwork based on this class
 * https://github.com/NTICompass/PHP-Base32
 *
 * @author Christian Riesen <chris.riesen@gmail.com>
 * @link http://christianriesen.com
 * @license MIT License see LICENSE file
 */
class Base32
{
 /**
  * Alphabet for encoding and decoding base32
  *
  * @var array
  */
 private static $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=';
 /**
  * Creates an array from a binary string into a given chunk size
  *
  * @param string $binaryString String to chunk
  * @param integer $bits Number of bits per chunk
  * @return array
  */
 private static function chunk($binaryString, $bits)
 {
  $binaryString = chunk_split($binaryString, $bits, ' ');
  if (substr($binaryString, (strlen($binaryString)) - 1) == ' ') {
   $binaryString = substr($binaryString, 0, strlen($binaryString)-1);
  }
  return explode(' ', $binaryString);
 }
 /**
  * Encodes into base32
  *
  * @param string $string Clear text string
  * @return string Base32 encoded string
  */
 public static function encode($string)
 {
  if (strlen($string) == 0) {
   // Gives an empty string
   return '';
  }
  // Convert string to binary
  $binaryString = '';
  foreach (str_split($string) as $s) {
   // Return each character as an 8-bit binary string
   $binaryString .= sprintf('%08b', ord($s));
  }
  // Break into 5-bit chunks, then break that into an array
  $binaryArray = self::chunk($binaryString, 5);
  // Pad array to be divisible by 8
  while (count($binaryArray) % 8 !== 0) {
   $binaryArray[] = null;
  }
  $base32String = '';
  // Encode in base32
  foreach ($binaryArray as $bin) {
   $char = 32;
   if (!is_null($bin)) {
    // Pad the binary strings
    $bin = str_pad($bin, 5, 0, STR_PAD_RIGHT);
    $char = bindec($bin);
   }
   // Base32 character
   $base32String .= self::$alphabet[$char];
  }
  return $base32String;
 }
 /**
  * Decodes base32
  *
  * @param string $base32String Base32 encoded string
  * @return string Clear text string
  */
 public static function decode($base32String)
 {
  // Only work in upper cases
  $base32String = strtoupper($base32String);
  // Remove anything that is not base32 alphabet
  $pattern = '/[^A-Z2-7]/';
  $base32String = preg_replace($pattern, '', $base32String);
  if (strlen($base32String) == 0) {
   // Gives an empty string
   return '';
  }
  $base32Array = str_split($base32String);
  $string = '';
  foreach ($base32Array as $str) {
   $char = strpos(self::$alphabet, $str);
   // Ignore the padding character
   if ($char !== 32) {
    $string .= sprintf('%05b', $char);
   }
  }
  while (strlen($string) %8 !== 0) {
   $string = substr($string, 0, strlen($string)-1);
  }
  $binaryArray = self::chunk($string, 8);
  $realString = '';
  foreach ($binaryArray as $bin) {
   // Pad each value to 8 bits
   $bin = str_pad($bin, 8, 0, STR_PAD_RIGHT);
   // Convert binary strings to ASCII
   $realString .= chr(bindec($bin));
  }
  return $realString;
 }
}

?>

将上述两个文件放置于 ThinkPHP 框架目录下的 ThinkPHP\Library\Vendor\oath 路径中,该 oath 目录需手动创建。

第二步:扩展数据库表结构以支持动态口令字段。

需在用户表中新增以下字段:auth_type(标识认证类型,0代表静态密码,1代表动态口令)、seed(主种子密钥)、temp_seed(临时种子密钥,用于开通前的暂存,认证成功后迁移至 seed)、last_logintime(上次成功登录时间)以及 last_otp(上次使用的动态口令值)。其中,auth_type 用于区分用户的认证模式;seed 存储正式种子密钥;temp_seed 作为未开通时的缓冲字段,一旦动态口令认证成功,其值将覆盖至 seed 字段;last_logintime 与 last_otp 则用于记录最近一次认证状态,旨在防止同一动态口令被重复使用。

第三步:代码层面的具体集成实现。

1)动态口令开通流程。

在原系统的修改密码页面增加认证方式的选择控件,例如:

这里写图片描述

当用户选择动态口令模式时,页面将展示一张兼容 Google Authenticator 格式的二维码,以便用户扫码绑定。二维码生成方法可参考《Thinkphp3.2.3整合phpqrcode生成带logo的二维码》一文。生成密钥二维码的核心代码如下:


public function qrcode()
 { 
  Vendor('oath.base32');
  $base32 = new \Base32();
  $rand = random(16);//生成随机种子
  $rand = $base32->encode($rand);
  $rand=str_replace('=','',$rand);//去除填充的‘='

  $errorCorrectionLevel =intval(3) ;//容错级别 
  $matrixPointSize = intval(8);//生成图片大小

  //生成二维码图片 
  Vendor('phpqrcode.phpqrcode');
  $object = new \QRcode();
  $text = sprintf("otpauth://totp/%s?secret=%s", $user, $rand);
  $object->png($text, false, $errorCorrectionLevel, $matrixPointSize, 2);

  生成的种子$rand保存到数据库的temp_seed字段
 }

random 函数用于生成随机字符串。代码 $rand=str_replace('=','',$rand) 的作用在于移除填充字符 '=',这是因为部分版本的谷歌手机令牌在 Base32 解码时不支持填充符。

验证用户输入动态口令的逻辑代码如下:


从数据库读取temp_seed
Vendor('oath.oath');
$object = new \Google2FA();
if($object->verify_key($temp_seed, $otp)){
 验证成功,将数据库更新seed为temp_seed,auth_type为1,last_otp为otp
}

2)动态口令登录验证。

用户尝试使用动态口令登录时的验证代码:

首先从数据库中读取 auth_type、seed 和 last_otp 三个关键字段。


if($auth_type==1){//动态口令
 //防止重复认证    
 if($lat_otp == $otp) {
  动态口令重复使用返回    
 }
 Vendor('oath.oath');
 $object = new \Google2FA();
 if(!$object->verify_key($seed, $otp))
 {
  动态口令不正确
 }
 else
 {
  登录成功,将数据库更新last_otp为$otp,last_logintime为time()
 }    
}

第四步:测试与验证环节。

下载并安装 Google Authenticator,先使用静态密码登录系统,随后进入修改密码页面。打开 Google Authenticator 应用扫描页面上显示的二维码,即可看到生成的动态口令。

这里写图片描述

这里写图片描述

保存设置后,动态口令开通即告成功!此时即可使用更为安全的动态口令登录系统。

以上即为本文的全部内容,希望对各位的学习有所帮助,也欢迎大家多多支持本站。

上一篇
Laravel 5.4 IoC容器注册自定义类的完整流程

本文介绍在 Laravel 5.4 框架中通过服务提供者向 IoC 容器注册自定义类的具体步骤。核心操作包括创建 Service Provider,在 register 方法中使用 $this->app->bind 将接口或字符串键绑定到具体实现类,并在 config/app.php 的 providers 数组中注册该服务提供者。完成配置后,即可在路由或其他组件中通过 app() 辅助函数获取实例,实现依赖注入与解耦。

下一篇
Debian系统禁用APT自动更新及PackageKit服务排查

Debian系统开机后出现持续的高带宽下载现象,经排查发现是APT包管理工具在后台执行自动更新。直接修改APT配置文件无效,因为底层由packagekit服务调用。通过禁用或移除packagekit.service可彻底解决该问题。

相关文章

更多
ThinkPHP 3.x 常量详解:预定义、路径与系统变量

本文整理了 ThinkPHP 3.x 框架中常用的三类常量,包括预定义常量、路径常量和系统常量。预定义常量如 URL 模式和关联类型固定不变;路径常量定义了核心类库、扩展目录及项目各模块的默认存放位置,支持自定义修改;系统常量则动态反映当前运行环境,如 CGI/WIN/CLI 模式、URL 地址结构、调试状态及模板主题等信息,帮助开发者准确获取运行时上下文。

2025.07.24 1,002
ThinkPHP乐观锁与悲观锁实现原理及代码示例

本文通过商品抢购场景解析ThinkPHP中的乐观锁与悲观锁机制。乐观锁利用version版本号在更新时校验数据一致性,防止超发但存在后买先成功的逻辑瑕疵;悲观锁则通过SELECT FOR UPDATE锁定行记录,确保事务串行执行。文中提供了基于MySQL的两种锁的具体SQL语句及PHP代码实现,帮助开发者根据业务需求选择合适的并发控制方案。

2026.07.17 999
ThinkPHP多层MVC架构详解:模型、视图与控制器的分层设计

ThinkPHP支持灵活的多层MVC设计,允许将应用拆分为模型、视图和控制器多个层级。模型层可细分为数据存取(Model)、业务逻辑(Logic)和服务接口(Service),通过D方法或M方法进行实例化调用,并支持配置默认层。视图层利用目录结构区分不同主题或终端风格,如移动端与PC端。控制器层分为核心调度器与业务控制器,甚至可引入事件控制器实现内外交互隔离。这种分层机制提升了代码的可维护性和扩展性,适应复杂项目需求。

2026.04.27 999
原生PHP与Laravel/ThinkPHP框架建站对比及快速上手建议

直接选择框架:需要快速开发、团队协作或长期维护,用 Laravel 或 ThinkPHP ;仅做简单脚本、无依赖环境或极致轻量场景,用原生 PHP 。

2026.03.01 998
ThinkPHP 3.2.3 文件上传功能详解与配置指南

本文介绍ThinkPHP 3.2.3框架中基于Think\Upload类的文件上传实现。涵盖多文件与单文件上传的表单配置,详细解析maxSize、exts等核心属性设置方法,以及通过函数或字符串自定义saveName命名规则和autoSub子目录保存机制,帮助开发者安全高效地处理附件上传业务。

2025.04.22 996
ThinkPHP模板替换规则与系统常量详解

ThinkPHP提供了一套默认的模板替换规则,将特定占位符映射为项目路径或URL地址。例如__ROOT__对应网站根目录,__APP__对应项目入口,__URL__对应模块地址。开发者可通过配置文件中的TMPL_PARSE_STRING变量自定义或覆盖这些规则,如修改__PUBLIC__指向/Common目录或新增__UPLOAD__上传路径。掌握这些常量机制有助于简化模板开发中的路径引用。

2025.04.20 991

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。