Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Very small implementation of Google's OTP Authenticator
<?php
// copied from python code at https://stackoverflow.com/a/23221582/3103058
function base32_decode($key) {
// https://www.php.net/manual/en/function.base-convert.php#122221
$key = strtoupper($key);
list($t, $b, $r) = array("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", "", "");
foreach(str_split($key) as $c)
$b = $b . sprintf("%05b", strpos($t, $c));
foreach(str_split($b, 8) as $c)
$r = $r . chr(bindec($c));
return($r);
}
function Truncate($hmac_sha1){
$offset = hexdec(substr($hmac_sha1, -1));
$binary = hexdec(substr($hmac_sha1, $offset * 2, 8)) & 0x7fffffff;
return $binary;
}
function HOTP($K, $C, $digits = 6) {
$decodeK = base32_decode($K);
$C_bytes = pack('J', $C);
$hmac_sha1 = hash_hmac("sha1", $C_bytes,$decodeK);
return substr(Truncate($hmac_sha1), -$digits);
}
function TOTP($K, $digits = 6, $window = 30) {
$C = (int)(time() / $window);
return HOTP($K, $C, $digits);
}
//produce OTP for key: "MZXW633PN5XW6MZX"
echo TOTP("MZXW633PN5XW6MZX");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.