I am trying to implement TOTP in PHP, and I get a six digit code, but it never matches the one in my Authenticator app. I was able to zero in on the problem being most likely related to the output of hash_hmac, since I tested all the bit shifting occurring after the hash is generated on the example in the RFC document and it produced the expected output. My question now is: What am I doing wrong? Am I passing the wrongly formatted input to hash_hmac? I am really at a loss here.
<?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);
}
}
?>
Some example input and output for TOTP::get(), where $this->secret is always " secret" and digits is always 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