Convert PFX to PEM


$pfx_file="mywindows_cert.pfx";
$password="dailyithlep";
$pem_file="mypem_cert.pem";
convert_pfx_file_to_pem($pfx_file,$password,$pem_file,true);
function convert_pfx_file_to_pem($pfx_file,$password,$pem_file,$remove_password=true)
{
$CERT_FILE="/tmp/certificate.crt";
$CA_CERT_FILE="/tmp/ca-cert.crt";
$PRIVATE_KEY="/tmp/private.key";
$PRIVATE_KEY_NOPASSWORD="/tmp/private_nopassword.key";

//get the certificate file from pfx file

$cmd=”openssl pkcs12 -clcerts -nokeys -in \”$pfx_file\” -out $CERT_FILE -passin pass:$password”;
shell_exec($cmd);

//get the ca-certificate file from pfx file
$cmd=”openssl pkcs12 -cacerts -nokeys -in \”$pfx_file\” -out $CA_CERT_FILE -passin pass:$password”;
shell_exec($cmd);
////get the private key from pfx file
$cmd=”openssl pkcs12 -nocerts -in \”$pfx_file\” -out $PRIVATE_KEY -passin pass:$password -passout pass:$password”;
shell_exec($cmd);
if($remove_password)
{
//remove the password in private key
$cmd=”openssl rsa -in $PRIVATE_KEY -out $PRIVATE_KEY_NOPASSWORD -passin pass:$password “;
shell_exec($cmd);
//put all 3 files into one file again
$cmd=”cat $CERT_FILE $CA_CERT_FILE $PRIVATE_KEY_NOPASSWORD > $pem_file “;
shell_exec($cmd);

}else{
//put all 3 files into one file again
$cmd=”cat $CERT_FILE $CA_CERT_FILE $PRIVATE_KEY > $pem_file “;
shell_exec($cmd);
}
@unlink($CERT_FILE);
@unlink($CA_CERT_FILE);
@unlink($PRIVATE_KEY);
@unlink($PRIVATE_KEY_NOPASSWORD);

$cmd=”openssl x509 -in $pem_file -text”;
echo shell_exec($cmd);
}

Leave a Reply

Your email address will not be published. Required fields are marked *