15261593499 2023-03-16 15:37:42

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

评论

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.123.4. UTC+08:00, 2024-04-18 00:02
浙ICP备14020137号-1 $访客地图$