Skip to content

Instantly share code, notes, and snippets.

@hilbix
Last active July 8, 2018 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hilbix/56e54dab48a16bf49f302b192baa10d9 to your computer and use it in GitHub Desktop.
Save hilbix/56e54dab48a16bf49f302b192baa10d9 to your computer and use it in GitHub Desktop.
PHP RFC4648-base32 to hex conversion for Google Authenticator
# $key = hex2bin(rfc4648tohex('AAAAAAAAAAAAAAAA')); # Your secret Auth-Key
# $token = googleauth($key, floor(time()/30));
function googleauth($key, $stamp)
{
$mac = hash_hmac('SHA1', substr(chr(0).chr(0).chr(0).chr(0).chr(0).chr(0).chr(0).pack('N', floor($stamp)),-8), $key, true);
$val = unpack('N', substr($mac, (ord(substr($mac, -1)) & 15), 4));
$val = $val[1]&0x7fffffff;
return substr("000000$val", -6);
}
# Input: base32hex
# Output: hex-string
function base32hex2hex($s)
{
$l = strlen($s);
if ($n = ($l%4))
$s = str_pad($s, $l+4-$n, '0', STR_PAD_LEFT);
$x = '';
foreach (str_split($s, 4) as $v)
$x .= str_pad(base_convert($v, 32, 16), 5, '0', STR_PAD_LEFT);
return $x;
}
# Input: string with RFC4648-base32
# Output: converted value into hex-string
function rfc4648tohex($s)
{
return base32hex2hex(strtr($s,
'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
'0123456789ABCDEFGHIJKLMNOPQRSTUV'
) );
}
@hilbix
Copy link
Author

hilbix commented Jul 7, 2018

I like short things which are easy to understand and to use. Not tested much, though (Google-Auth thingie works so far at my side).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment