Bootstrap

PHP的HMAC_SHA1和HMAC_MD5算法方法

很多做对接的小伙伴们都会遇到签名加密的问题,常用的就是hmac_sha1加密和hmac_md5加密,最开始用的是sha1加密,后来用到了md5加密,我以为直接把sha1改为md5就好了,结果试来试去跟文档提示的示例结果都对不上,最后经过查询搜索终于得到了正确的方法,现在把两种加密方法分享给大家

function do_hmac_sha1($str, $key) {
	$signature = "";
	if (function_exists('hash_hmac')) {
		$signature = base64_encode(hash_hmac("sha1", $str, $key, true));
	} else {
		$blocksize = 64;
		$hashfunc = 'sha1';
		if (strlen($key) > $blocksize) {
			$key = pack('H*', $hashfunc($key));
		}
		$key = str_pad($key, $blocksize, chr(0x00));
		$ipad = str_repeat(chr(0x36), $blocksize);
		$opad = str_repeat(chr(0x5c), $blocksize);
		$hmac = pack(
		                'H*', $hashfunc(
		                    ($key ^ $opad) . pack(
		                        'H*', $hashfunc(
		                            ($key ^ $ipad) . $str
		                        )
		                    )
		                )
		            );
		$signature = base64_encode($hmac);
	}
	return $signature;
}
function do_hmac_md5($data, $key) {
	if (function_exists('hash_hmac')) {
		return hash_hmac('md5', $data, $key);
	}
	$bytelen = 64;
	// byte length for md5
	if (strlen($key) > $bytelen) {
		$key = pack('H*', md5($key));
	}
	$key = str_pad($key, $bytelen, chr(0x00));
	$ipad = str_pad('', $bytelen, chr(0x36));
	$opad = str_pad('', $bytelen, chr(0x5c));
	$k_ipad = $key ^ $ipad;
	$k_opad = $key ^ $opad;
	return md5($k_opad . pack('H*', md5($k_ipad . $data)));
}

;