PHP RSA算法 HMAC-SHA1加密算法

HMAC-SHA1加密算法

function getSignature($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;
}

php openssl(SHA1WithRSA) 签名 验签

签名:

public function wjSign($data){
    $key = openssl_pkey_get_private(file_get_contents($this->privateKeyPathWJ));
    openssl_sign($data, $sign, $key, OPENSSL_ALGO_SHA1);
    $sign = base64_encode($sign);
    return $sign;
}

验签:

public function wjVerify($data, $sign){
    $sign = base64_decode($sign);
    $key = openssl_pkey_get_public(file_get_contents($this->publicKeyPathWJ));
    $result = openssl_verify($data, $sign, $key, OPENSSL_ALGO_SHA1) === 1;
    return $result;
}

 

posted @ 2017-03-16 11:33  张志健  阅读(2922)  评论(0编辑  收藏  举报