Skip to content

Instantly share code, notes, and snippets.

@Cojad
Last active July 5, 2023 09:15
Show Gist options
  • Save Cojad/71d1c9fc835eb225b075cb1a9cd6a780 to your computer and use it in GitHub Desktop.
Save Cojad/71d1c9fc835eb225b075cb1a9cd6a780 to your computer and use it in GitHub Desktop.
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);
$C_bytes = pack('N', 0) . pack('N', $C); //work with PHP version < 5.6.3
$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