IT评测·应用市场-qidao123.com技术社区
标题:
PHP的HMAC_SHA1和HMAC_MD5算法方法
[打印本页]
作者:
北冰洋以北
时间:
2025-1-18 13:02
标题:
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)));
}
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/)
Powered by Discuz! X3.4