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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM