繁体   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