HMAC-SHA1、HMAC-MD5等算法,在PHP5.1.X之后,可直接使用如下形式来计算
echo hash_hmac(’sha1’,$data,$key);
如果加载了MHASH扩展,也可直接使用mhash来进行运算
echo bin2hex(mhash(MHASH_SHA1, $data, $key));
如果PHP版本低于5.1.X或者没有加载Mhash、或HMAC扩展,可使用如下的通用方法来进行相应运算
function hmac($key, $data, $hash="md5") {
$b = 64;
if (strlen($key) > $b)
$key = pack("H*", call_user_func($hash, $key));
$key = str_pad($key, $b, chr(0x00));
$ipad = str_pad("", $b, chr(0x36));
$opad = str_pad("", $b, chr(0x5c));
$k_ipad = $key ^ $ipad ;
$k_opad = $key ^ $opad;
return call_user_func($hash, $k_opad . pack("H*", call_user_func($hash, $k_ipad . $data)));
}
echo hmac($key,$data,’sha1’);