PHP-Rsa分段加密解密(ThinkPHP5)

<?php
/**

 * 电子保单查示例
 */

namespace app\inter\controller;

class Demo
{

    /*I云服配置*/
    protected $partner = '54**55';  /*正式版*/
    protected $key = 'iyb91e**5869a98';  /*正式版*/
    protected $dianzibaodan='https://open.firstbx.com/open/v3/route/baoyunChkEncryptSign'; /*正式版*/
    protected $uniqueid='C4IpXquJ**P3PrjOPDbPq'; /*正式版*/
    protected $publickey='MIGfMA0GCSq**DQEBAQUAA4GNADCBiQKBgQCyzA4ZV7+hQxkaBKxaOxB1r7roIcc5npvf+uMkpkmm8x1ALp/zoeXK83Vuda/ZU0mnAu5IVR4VovDAM6A5Aea2GLBkJbGisMX0LcpCBNYWkTrXK7VarH05oJWuO0nP7leGHg2zB0IS0PRj2v8MoDci8PeRaAQiUaDjB1ZZkpeO4QIDAQAB'; /*正式版*/
    protected $selfkey='MIICdwIBADAN**hkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKeAZpfNjU3aTuOfkjA1HppEA52CMZdA2uJLCyzFp4yexbvdpuBiVl2tP5bvrkcXeYHEJxNyxrwKeGcyzXoaC7IDFrXOwDrF964Dsx2CXJcoCqx2Q7uCMKIBrCsHdM3V6U9A2ceS34VUkIZ4pfv7QbFofLsQpHf2EDTAMGS29P4lAgMBAAECgYBP6xaIFV33KFL9jfQtJhsc1Zi3/Rd2KE6HK/EAAqpnkJWdhisJ4kF83p15gZAwgUXLIXDXearSq1g5POcG/AhZtI98QIJWXZeiiCOayfxz6mrvIJMAmonThPOQVg+Rl+AEA160ne5MSdQAVtICeiWU3DkyxX3QziX43gYYRo+rHQJBAPsfwCtOqjyq0x8tl/VJlqz2xspDxQIlkfzgj38sZOQh9IgRSKC8Oq0gzQQVgGj0YR04BINkXnAuXyvLawmuyeMCQQCqwP4BcTJ8ASYNJxOoFMuvCKbjvoXG3Zl9JNXmlO2+FLTPA2S3tTDUxhaEx69zjRL5jaKLk09m7cmHRVzdjbZXAkEA5+47HcRZlg5vTqxdXD3K25RPpR9SJNluK496+ImX5Ns3bTQJT+qIhr10nAD/x+9sgf/qqy9XyWQKofgNs7Oq4QJABgQYrupTEgVkVtBKpABfkMIoRxveULxb/QnAM4iJu8m0+RowgTx0BPsZrgHvD44n3fz8fhhpksHL+OUbuX6VrwJBAKQl6s/q803PAWHQjvpmdF7aj3pHJXFeTkhmHNKlmk8kaj7v9TNTe1GWRdUjcyrLTftINHRO2dgzEHQZITnMo6k='; /*正式版*/


    /*RSA分段加密*/
    protected  function iyyencrypt($originalData){
        $publicKey =  self::get_public_key($this->publickey);
        $crypto = '';
        foreach (str_split($originalData, 117) as $chunk) {
            $encryptData = '';
            if(openssl_public_encrypt($chunk, $encryptData, $publicKey)){
                $crypto .= $encryptData;
            }else{
                die('加密失败');
            }
        }
        return base64_encode($crypto);
    }

    /*RSA分段解密*/
    protected function iyydecrypt($encryptData){
        $privateKey = self::get_private_key($this->selfkey);
        $decryptData = '';
        $crypto = '';
        foreach (str_split(base64_decode($encryptData), 128) as $chunk) {
            if(openssl_private_decrypt($chunk, $decryptData, $privateKey)){
                $crypto .= $decryptData;
            }else{
                die('解密失败');
            }
        }
        return $crypto;
    }


    /**获取私有key字符串 重新格式化  为保证任何key都可以识别*/
    protected function get_private_key($private_key){
        $search = array(
            "-----BEGIN RSA PRIVATE KEY-----",       //自定义头部
            "-----END RSA PRIVATE KEY-----",         //自定义尾部
            "\n",
            "\r",
            "\r\n"
        );
        $private_key=str_replace($search,"",$private_key);
        return $search[0] . PHP_EOL . wordwrap($private_key, 64, "\n", true) . PHP_EOL .$search[1];
    }

    /**获取公共key字符串  重新格式化 为保证任何key都可以识别*/
    protected function get_public_key($public_key){
        $search = array(
            "-----BEGIN PUBLIC KEY-----",          //自定义头部
            "-----END PUBLIC KEY-----",            //自定义尾部
            "\n",
            "\r",
            "\r\n"
        );
        $public_key=str_replace($search,"",$public_key);
        return $search[0] . PHP_EOL . wordwrap($public_key, 64, "\n", true) . PHP_EOL . $search[1];
    }

    /**
     * @param $data
     * @return string
     *  生成签名
     */
    protected function setSign($data){
        return md5($data.$this->key);
    }


    /**
     * @param string $url post请求地址
     * @param array $params
     * @return mixed
     */
    protected function curl_post($url, array $params = array())
    {
        $data_string = json_encode($params);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt(
            $ch, CURLOPT_HTTPHEADER,
            array(
                'Content-Type: application/json'
            )
        );
        $data = curl_exec($ch);
        curl_close($ch);
        return ($data);
    }




    /**
     *  电子保单查询  IH1100015011824503
     *  RSA 加密解密是核心  https://www.cnblogs.com/makalochen/p/10845033.html
     */
    public function getPolicyList(){
        $params = Request::instance()->param();   /*接收数据,不同框架不一样,这个是用的TP5*/
        $data = [
            'uniqueId'    =>  $this->uniqueid,
            'policyNo'    =>  $params['policyNo'],
            'partner'       =>  $this->partner,
            'queryType'    =>  'newElectronicPolicy'
        ];
        $data=self::iyyencrypt(json_encode($data));

        $sign = self::setSign($data);
        $parameter['data'] = $data;
        $parameter['sign'] = $sign;
        $parameter['partner'] = $this->partner;
        $rest = self::curl_post($this->dianzibaodan,$parameter);

        $result = json_decode($rest,true);

//        string(355) "{"insurantName":"俞帅","finishTime":"2022-01-19
//23:59:59.0","policyId":"236501959","attributorName":"李秀珍","effectiveTime":"2021-01-20
//00:00:00.0","electronicPolicyUrl":"https://passport-uat.iyunbao.com/m/auth/common_auth_message?token=1366689652517371904","policyNo":"IH1100015011824503","applicantName":"俞帅","productName":"尊享e生2020版"}"

        if ($result['code']==0){
            //私钥解密
            $datas=self::iyydecrypt($result['data']);
            $datainfo=json_decode($datas,true);
            if($datainfo['electronicPolicyUrl']){
                return json(['code'=>1,'data'=>$datainfo,'msg'=>'成功']);
            }else{
                return json(['code'=>0,'msg'=>'暂无电子保单','data'=>'']);
            }
        }else{
            return json(['code'=>0,'msg'=>'接口调用失败...','data'=>'']);
        }

    }


}

本文由 我爱PHP169 作者:admin 发表,其版权均为 我爱PHP169 所有,文章内容系作者个人观点,不代表 我爱PHP169 对观点赞同或支持。如需转载,请注明文章来源。

发表回复