虚心使人进步

虚心学习,天天向上......
随笔 - 274, 文章 - 2, 评论 - 161, 阅读 - 76万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

php自动转换pfx到pem和cer(dem格式)到pem

Posted on   Showker  阅读(10013)  评论(3编辑  收藏  举报

经常做银行的支付接口,私钥一般都是pfx格式(私钥用来加密生成签名发送报文),公钥是cer格式(公钥用来验证返回报文里的签名)。但是php里openssl只能用pem格式,每次转换都要用openssl命令在本地转好,很是麻烦。下面是直接php转换的代码。

 

私钥pfx转pem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function verifyReturn($data,$signature,$filePath){
 
/*<br>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;
}

  

编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示