php代码
function hmacmd5($data,$key) { // rfc 2104 hmac implementation for php. // creates an md5 hmac. // eliminates the need to install mhash to compute a hmac // hacked by lance rushing(note: hacked means written) //需要配置环境支持iconv,否则中文参数不能正常处理 $key = iconv(gb2312,utf-8,$key); $data = iconv(gb2312,utf-8,$data); $b = 64; // byte length for md5 if (strlen($key) > $b) { $key = pack(h*,md5($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 md5($k_opad . pack(h*,md5($k_ipad . $data))); }
hmac需要一个加密用散列函数(表示为h)和一个密钥k。
假设h是一个将数据块用一个基本的迭代压缩函数来加密的散列函数。
用b来表示数据块的长。(以上说提到的散列函数的分割数据块长b=64),用l来表示散列函数的输出数据长(md5中l=16,sha?1中l=20)。
密钥的长度可以是小于等于数据块长的任何正整数值。应用程序中使用的密钥长度若是比b大,则首先用使用散列
函数h作用于它,然后用h输出的l长度字符串作为在hmac中实际使用的密钥。
一般情况下,推荐的最小密钥k长度是l长。(与h的输出数据长度相等)。
转自:http://blog.icain.cn/show-199-1.html