Reputation: 2479
How can I convert .pfx (PKCS12 or .p12) certificate to .crt and .pem using PHP OpenSSL functions, so I avoid commandline tools, which are not allowed on my public server.
Upvotes: 2
Views: 3976
Reputation: 7862
You can use open the OpenSSL functions provided by PHP:
$pathPfxCertificate = "foo/bar/certificate.pfx";
$passwordCertificate = "123456";
// Attempt to read the PKCS12 certificate file using OpenSSL
$certificateStoreData = [];
$readedSuccessful = openssl_pkcs12_read(
file_get_contents($pathPfxCertificate),
$certificateStoreData,
$passwordCertificate
);
if ($readedSuccessful == false) {
throw new \Exception("Error: " . openssl_error_string());
}
// We read the data provided by `openssl_pkcs12_read` and assemble the content of the PEM certificate.
$contentPemCertificate = $certificateStoreData["pkey"];
$contentPemCertificate .= $certificateStoreData["cert"];
$contentPemCertificate .= ($certificateStoreData["extracerts"][1] ?? "");
$contentPemCertificate .= ($certificateStoreData["extracerts"][0] ?? "");
file_put_contents("foo/bar/certificate.pem", $contentPemCertificate);
Documentation:
Upvotes: 0
Reputation: 2479
<?php
$res = [];
$openSSL = openssl_pkcs12_read($pkcs12, $res, $cert_password);
if(!$openSSL) {
throw new ClientException("Error: ".openssl_error_string());
}
// this is the CER FILE
file_put_contents('CERT.cer', $res['pkey'].$res['cert'].implode('', $res['extracerts']));
// this is the PEM FILE
$cert = $res['cert'].implode('', $res['extracerts']);
file_put_contents('KEY.pem', $cert);
Upvotes: 2