我正在尝试在 PHP 中实现 TOTP,我得到了一个六位数的代码,但它与我的 Authenticator 应用程序中的代码不匹配。我能够将最有可能与 hash_hmac 的输出相关的问题归零,因为我测试了在 RFC 文档中的示例上生成哈希后发生的所有位移,并产生了预期的输出。我现在的问题是:我做错了什么?我是否将错误格式的输入传递给 hash_hmac?我在这里真的很茫然。
<?php
class TOTP
{
function __construct ($d, $k)
{
$this->digits = $d;
$this->secret = $k;
$this->ival = 30;
}
private function int2bytes ($n)
{
$bytes = array();
for ($i = 7; $i >= 0; $i--) {
$bytes[] = ($n >> ($i * 8)) & 0xff;
}
return pack("C*", ...$bytes);
}
function hotp ($d, $k, $c)
{
// @$d the number of digits
// @$k the shared secret
// @$c an integer counter
$hmac = hash_hmac("sha1", $this->int2bytes($c), $k);
$hex = str_split($hmac, 2);
$bytes = array();
for ($i = 0; $i < count($hex); $i++) {
$bytes[] = hexdec($hex[$i]);
}
$offset = $bytes[19] & 0xf;
$bincode =
($bytes[$offset] & 0x7f) << 24 |
($bytes[$offset + 1] & 0xff) << 16|
($bytes[$offset + 2] & 0xff) << 8 |
$bytes[$offset + 3] & 0xff;
$hotp = strval($bincode % pow(10, $d));
while (strlen($hotp) < $d) {
$hotp = "0$hotp";
}
return $hotp;
}
public function get ()
{
$counter = floor(time() / $this->ival);
return $this->hotp($this->digits, $this->secret, $counter);
}
}
?>
TOTP::get() 的一些示例输入和输出,其中 $this->secret 始终为“secret”且数字始终为 6:
unix time: 1584041829
output: 79 06 09
expected: 91 97 63
unix time: 1584041867
output: 76 89 74
expected: 70 54 64
unix time: 1584041918
output: 46 57 96
expected: 52 96 15