SHA256WithRSA 生成签名

SHA256WithRSA 生成签名

//取出从api开始后面的方法
$path = parse_url('https://baidu.com:9443/api/pmss/doSendTransferMsg/v1',PHP_URL_PATH);

$params['app_id'] = 'appid12344567';
$params['msg_id'] = uniqid();
$params['fmt_type'] = 'json';
$params['charset'] = 'UTF-8';
$params['timestamp'] = date('Y-m-d H:i:s');
$strToSign = $this->buildOrderedSignStr($path, $params);
$signedStr = $this->sign($strToSign, 'SHA256WithRSA', $PRIVATE_KEY, 'UTF-8');
$params['sign'] = $signedStr;

//将筛选的参数按照第一个字符的键值 ASCII 码递增排序(字母升序排序),如果遇到相同字符则按照第二个字符的键值 ASCII 码递增排序,以此类推
//将排序后的参数与其对应值,组合成“参数=参数值”的格式,并且把这些参数用&字符连接起来,此时生成的字符串为待签名字符串
public function buildOrderedSignStr($path,$params){
        $isSorted = ksort ( $params );
        $comSignStr = $path . '?';

        $hasParam = false;
        foreach ( $params as $key => $value ) {
            if (null == $key || "" == $key || null == $value || "" == $value) {
            } else {
                if ($hasParam) {
                    $comSignStr = $comSignStr . '&';

                } else {
                    $hasParam = true;
                }

                $comSignStr = $comSignStr . $key . '=' . $value;
                // 	print_r($comSignStr);
                // print_r('<hr>');

            }
        }

        return $comSignStr;
    }

//选择签名方式
public function sign($strToSign, $signType, $privateKey){
	return $this->rsa($strToSign,$privateKey,$signType);
}

//开始签名
public function rsa($content,$privateKey,$algorithm){
        $signature = "";

        if( $algorithm == 'SHA1WithRSA'){
            openssl_sign($content,$signature,"-----BEGIN PRIVATE KEY-----\n".wordwrap($privateKey,64,"\n",true)."\n-----END PRIVATE KEY-----", OPENSSL_ALGO_SHA1);
        }elseif ($algorithm == 'SHA256WithRSA') {
            //  print_r(111);
            openssl_sign($content,$signature,"-----BEGIN PRIVATE KEY-----\n".wordwrap($privateKey,64,"\n",true)."\n-----END PRIVATE KEY-----",OPENSSL_ALGO_SHA256);
        }else{
            throw new Exception("Only support OPENSSL_ALGO_SHA1 or OPENSSL_ALGO_SHA256 algorithm signature!");
        }
        return base64_encode($signature);
    }

相关文章

SHA256WithRSA 生成签名
消息推送
简单
set_time_limit 不会把已经执行的时间 和 sleep 的时间计算在...
金xlua
php分解代码片段$colors  = "red,blue,...