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));