Search code examples
phpopensslcertificate

How to convert PFX to CRT and PEM using PHP?


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.


Solution

  • <?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);