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就好了,效果试来试去跟文档提示的示例效果都对不上,最后颠末查询搜索终于得到了正确的方法,如今把两种加密方法分享给各人
  1. function do_hmac_sha1($str, $key) {
  2.         $signature = "";
  3.         if (function_exists('hash_hmac')) {
  4.                 $signature = base64_encode(hash_hmac("sha1", $str, $key, true));
  5.         } else {
  6.                 $blocksize = 64;
  7.                 $hashfunc = 'sha1';
  8.                 if (strlen($key) > $blocksize) {
  9.                         $key = pack('H*', $hashfunc($key));
  10.                 }
  11.                 $key = str_pad($key, $blocksize, chr(0x00));
  12.                 $ipad = str_repeat(chr(0x36), $blocksize);
  13.                 $opad = str_repeat(chr(0x5c), $blocksize);
  14.                 $hmac = pack(
  15.                                 'H*', $hashfunc(
  16.                                     ($key ^ $opad) . pack(
  17.                                         'H*', $hashfunc(
  18.                                             ($key ^ $ipad) . $str
  19.                                         )
  20.                                     )
  21.                                 )
  22.                             );
  23.                 $signature = base64_encode($hmac);
  24.         }
  25.         return $signature;
  26. }
复制代码
  1. function do_hmac_md5($data, $key) {
  2.         if (function_exists('hash_hmac')) {
  3.                 return hash_hmac('md5', $data, $key);
  4.         }
  5.         $bytelen = 64;
  6.         // byte length for md5
  7.         if (strlen($key) > $bytelen) {
  8.                 $key = pack('H*', md5($key));
  9.         }
  10.         $key = str_pad($key, $bytelen, chr(0x00));
  11.         $ipad = str_pad('', $bytelen, chr(0x36));
  12.         $opad = str_pad('', $bytelen, chr(0x5c));
  13.         $k_ipad = $key ^ $ipad;
  14.         $k_opad = $key ^ $opad;
  15.         return md5($k_opad . pack('H*', md5($k_ipad . $data)));
  16. }
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4