Skip to content

Instantly share code, notes, and snippets.

@markuszeller
Last active October 1, 2022 18:34
Show Gist options
  • Save markuszeller/d1e635d75cd3865d0f2823b672467a96 to your computer and use it in GitHub Desktop.
Save markuszeller/d1e635d75cd3865d0f2823b672467a96 to your computer and use it in GitHub Desktop.
Timed one time password
<?php
$digits = 6;
$interval = 30;
$secret = 'secret_key';
$prevTotp = '';
for ($i = 0; $i < $interval * 4; $i++) {
$time = time();
$counter = (string) floor($time / $interval);
$hmac = hash_hmac('sha1', $counter, $secret);
$offset = hexdec(substr($hmac, -1, 1));
$otp = hexdec(substr($hmac, $offset * 2, 8));
$totp = sprintf('%06d', $otp % 10 ** $digits);
if ($totp !== $prevTotp) {
$prevTotp = $totp;
echo PHP_EOL;
}
printf("\r\e[2KTime: %d\tCounter: %d\tTOTP: %0{$digits}d", $time, $counter, $totp);
sleep(1);
}
echo PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment