Generate PHP HMAC Hash Without Hash Extension
September 11th, 2009The other day, I ran into a problem with one of my web hosts… The version of PHP installed on the server didn’t have access to the Hash extension and I needed to generate an HMAC hash. Eight hours and many test runs later, I managed to produce a function that generates identical output to PHP5′s built-in hash_hmac function.
function custom_hmac($algo, $data, $key, $raw_output = false)
{
$algo = strtolower($algo);
$pack = 'H'.strlen($algo('test'));
$size = 64;
$opad = str_repeat(chr(0x5C), $size);
$ipad = str_repeat(chr(0x36), $size);
if (strlen($key) > $size) {
$key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
} else {
$key = str_pad($key, $size, chr(0x00));
}
for ($i = 0; $i < strlen($key) - 1; $i++) {
$opad[$i] = $opad[$i] ^ $key[$i];
$ipad[$i] = $ipad[$i] ^ $key[$i];
}
$output = $algo($opad.pack($pack, $algo($ipad.$data)));
return ($raw_output) ? pack($pack, $output) : $output;
}
I have verified that this code works in both PHP4 and PHP5 on my server, but it may perform differently depending on your version. Feel free to use it, modify it, etc. however you wish.
Leave a Reply