Verify a TOTP code (authenticator app)

The same maths as Google Authenticator (RFC 6238). Allow one step either side for clock drift.

PHP · Verify a TOTP code (authenticator app)Advanced
function base32Decode(string $s): string
{
    $map = array_flip(str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'));
    $bits = '';
    foreach (str_split(strtoupper(rtrim($s, '='))) as $ch) {
        $bits .= str_pad(decbin($map[$ch] ?? 0), 5, '0', STR_PAD_LEFT);
    }
    $out = '';
    foreach (str_split($bits, 8) as $byte) {
        if (strlen($byte) === 8) $out .= chr(bindec($byte));
    }
    return $out;
}

function totp(string $secret, ?int $time = null, int $digits = 6, int $period = 30): string
{
    $counter = intdiv($time ?? time(), $period);
    $hash = hash_hmac('sha1', pack('J', $counter), base32Decode($secret), true);
    $o = ord($hash[19]) & 0x0f;
    $n = ((ord($hash[$o]) & 0x7f) << 24) | (ord($hash[$o + 1]) << 16) | (ord($hash[$o + 2]) << 8) | ord($hash[$o + 3]);
    return str_pad((string)($n % (10 ** $digits)), $digits, '0', STR_PAD_LEFT);
}

function totpVerify(string $secret, string $code, int $drift = 1): bool
{
    for ($i = -$drift; $i <= $drift; $i++) {
        if (hash_equals(totp($secret, time() + $i * 30), $code)) return true;
    }
    return false;
}
totp2fasecurityhmac