php实现双因素身份验证2FA的TOTP一次性密码生成算法代码
代码语言:php
所属分类:其他
代码描述:php实现双因素身份验证2FA的TOTP一次性密码生成算法代码,TOTP是Time-based One-Time Password,基于时间的一次性密码生成器。
代码标签: php 双因素 身份 验证 2FA TOTP 一次性 密码 生成 算法 代码
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<?php class TOTP { private $secret; private $digits; private $period; public function __construct($secret = null, $digits = 6, $period = 30) { $this->secret = $secret ?: $this->generateSecret(); $this->digits = $digits; $this->period = $period; } public function generateSecret($length = 16) { $validChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; $secret = ''; for ($i = 0; $i < $length; $i++) { $secret .= $validChars[random_int(0, strlen($validChars) - 1)]; } return $secret; } public function getSecret() { return $this->secret; } public function generateCode($timestamp = null) { if ($timestamp === null) { $timestamp = time(); } $timeSlice = floor($timestamp / $this->period); $secretKey = $this->base32Decode($this->secret); $time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice); $hm = hash_hmac('SHA1', $time, $secretKey, true); $offset = ord(substr($hm, -1)) & 0x0F; $hashpart = substr($hm, $offset, 4); $value = unpack('N', $hashpart); $value = $value[1]; $value = $value & 0x7FFFFFFF; $modulo = pow(10, $this->digits); return str_pad($value % $modulo, $this->digits, '0', STR_PAD_LEFT); } public function verifyCode($code, $timestamp = null) { if ($timestamp === null) { $timestamp = time(); } for ($i = -1; $i <= 1; $i++) { if ($this->generateCode($timestamp + ($i * $this->period)) == $code) { return true; } } return false; } private function base32Decode($secret) .........完整代码请登录后点击上方下载按钮下载查看
网友评论0