-
-
Save asika32764/2e0e3606cd7e5bbbc528488c79edbcf5 to your computer and use it in GitHub Desktop.
Very small implementation of Google's OTP Authenticator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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