php自動轉換pfx到pem和cer(dem格式)到pem


經常做銀行的支付接口,私鑰一般都是pfx格式(私鑰用來加密生成簽名發送報文),公鑰是cer格式(公鑰用來驗證返回報文里的簽名)。但是php里openssl只能用pem格式,每次轉換都要用openssl命令在本地轉好,很是麻煩。下面是直接php轉換的代碼。

 

私鑰pfx轉pem

//filePath為pfx文件路徑
function signfrompfx($strData,$filePath,$keyPass)
    {
      
        if(!file_exists($filePath)) {
            return false;
        }
 
        $pkcs12 = file_get_contents($filePath);

        if (openssl_pkcs12_read($pkcs12, $certs, $keyPass)) {
            $privateKey = $certs['pkey'];



            $publicKey = $certs['cert'];
            $signedMsg = "";
            if (openssl_sign($strData, $signedMsg, $privateKey)) {
        $signedMsg=bin2hex($signedMsg);//這個看情況。有些不需要轉換成16進制,有些需要base64編碼。看各個接口
                return $signedMsg;
            } else {
                return '';
            }
        } else {
            return '0';
        }
    } 

  公鑰cer轉pem(即x.509證書dem格式轉換為pem)

function verifyReturn($data,$signature,$filePath){

/*
filePath為crt,cert文件路徑。x.509證書 cer to dem, Convert .cer to .pem, cURL uses .pem */ $certificateCAcerContent = file_get_contents($filePath); $certificateCApemContent = '-----BEGIN CERTIFICATE-----'.PHP_EOL .chunk_split(base64_encode($certificateCAcerContent), 64, PHP_EOL) .'-----END CERTIFICATE-----'.PHP_EOL;*/ $pubkeyid = openssl_get_publickey($certificateCApemContent); $len = strlen($signature); $signature= pack("H" . $len, $signature); //Php-16進制轉換為2進制,看情況。有些接口不需要,有些需要base64解碼 $data=str_replace('<?xml version=\"1.0\" encoding=\"GBK\"?>', '<?xml version="1.0" encoding="GBK"?>', $data);//這個看情況。 // state whether signature is okay or not $ok = openssl_verify($data, $signature, $pubkeyid); openssl_free_key($pubkeyid); return $ok; }

  


免責聲明!

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



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