zoukankan      html  css  js  c++  java
  • PHP中对hmac_sha1签名算法的实现方法

    最近研究网宿云文档API,其中用到了一种叫hmac_sha1的签名算法;

    HMAC-SHA1:

    HMAC是哈希运算消息认证码 (Hash-based Message Authentication Code),HMAC运算利用哈希算法,以一个密钥和一个消息为输入,生成一个消息摘要作为输出。HMAC-SHA1签名算法是一种常用的签名算法,用于对一段信息进行生成签名摘要。

    PHP代码实现:

        /**
         * 获取hmac_sha1签名的值
         * @link 代码来自: http://www.educity.cn/develop/406138.html
         *
         * @param $str 源串
         * @param $key 密钥
         *
         * @return 签名值
         */
        function 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;
        }
    }

    注:自PHP5.1.2起就已经内置了hash_hmac函数,所以可不必做function_exsits的判断,一行代码便可获取hmac_sha1签名值:

    $signature = base64_encode(hash_hmac("sha1", $str, $key, true));
  • 相关阅读:
    美团数据治理参考
    Ignite(三): Ignite VS Spark
    Ignite(二): 架构及工具
    Sqlserver 计算两坐标距离函数
    Ignite(一): 概述
    IMDG
    锂电池不一致而产生危害
    平均数_中位数_众数在SqlServer实现
    怎样给孩子取一个好名字?搜狗“有名堂”大数据支招
    eclipse导入外部jar包
  • 原文地址:https://www.cnblogs.com/AllenChou/p/7651306.html
Copyright © 2011-2022 走看看