簡體   English   中英

使用 PHP OPENSSL 從 PFX 證書中提取公鑰到 .cer 文件

[英]Extract public key from a PFX certificate to a .cer file with PHP OPENSSL

我正在嘗試創建一個加密 PHP-OPENSSL 模塊來簽署數據並與第三方應用程序通信。 為此,我有一個數字 .PFX 證書 (cert.pfx)。

我可以用我的密碼打開它並使用 openssl_pkcs12_read() 讀取它。

第三方應用程序的設置要求我上傳證書的 .cer 公鑰。

因為,我只有一個 .pfx 文件。 我正在嘗試從 PFX 中提取 .cer 公鑰來創建和上傳 .cer 文件。

我正在使用 PHP-OPENSSL。

我試圖用這個命令來做到這一點:

 $pkeydet = openssl_pkey_get_details(openssl_pkey_get_public(file_get_contents("/path/to/cert.pfx")));

但它沒有給出預期的結果( openssl_pkey_get_details() 期望參數 1 是資源,給定的布爾值)。 我不確定為什么...

這是實現.cer文件創建的正確方法是什么?

謝謝 :)

我想我找到了解決方案,我需要進行從 PFX 到 PEM 到 CER 的轉換,因為函數 openssl_pkey_get_details() 僅適用於 .pem 證書。

這是我所做的:

$pass = "thisismypass"; // my pfx is pwd protected
$cert_info = array();

我讀了證書

if (!$cert_store = file_get_contents(/path/to/cert.pfx")) {
echo "Error: Unable to read the cert file\n";
exit;
}

if (openssl_pkcs12_read($cert_store, $cert_info, $pass)) {
echo "Certificate loaded\n";
}else{
echo "Error: Unable to read the cert store.\n";
exit;
}

我寫 .CER 證書

$cert = $cert_info['pkey'].$cert_info['cert'].implode('', $cert_info['extracerts']);
file_put_contents(/path/to/cert.cer',$cert);

我寫了 .PEM 證書

$cert = $cert_info['cert'].implode('', $cert_info['extracerts']);
file_put_contents(/path/to/cert.pem', $cert);

現在,我可以從 .PEM 中提取公鑰:

$pkeydet = openssl_pkey_get_details(openssl_pkey_get_public(file_get_contents(/path/to/cert.pem')));
file_put_contents(/path/to/publick.pem', $pkeydet['key']);

因為我的 .CER PK 應該是二進制的,所以我需要使用 php.net 上的這個函數進行轉換:

function pem2der($pem_data){
   $begin = "KEY-----";
   $end   = "-----END";
   $pem_data = substr($pem_data, strpos($pem_data, $begin)+strlen($begin));   
   $pem_data = substr($pem_data, 0, strpos($pem_data, $end));
   $der = base64_decode($pem_data);
   return $der;
}

$pem_data = file_get_contents(/path/to/publick.pem');
$pem2der = pem2der($pem_data);
file_put_contents(/path/to/publick.cer', $pem2der);

注意:我讀到 .cer 文件可以是二進制文件,也可以不是

我希望它是正確的。 我尚未測試生成的 CER,但我認為我可能接近解決方案!

歡迎任何意見/建議:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM