How to seamlessly convert PFX encoded certificate file to PEM format using OpenSSL?

PKCS #12 is an archive file format used for storing multiple cryptography objects in a single file. The filename extension for PKCS #12 files is .p12 or .pfx. This format is often used to bundle a PEM certificate and its corresponding private key, along with any additional CA chain certificates.
A .pfx file is a bag that can hold many objects with optional password protection; however, a PKCS#12 archive usually contains a certificate and the corresponding private key. The file can also include CA chain certificates as well. When creating a PFX file, a PFX password may be set to protect the contents of the file, ensuring that only authorized users can access the sensitive information it contains.
PEM is a base64 encoded certificate placed between the headers —–BEGIN CERTIFICATE—– and —–END CERTIFICATE—–. The following file extensions are possible for PEM certificates:*.pem, *.crt, and *.cer
The following procedure will convert the PFX-encoded certificate file into two files in PEM format.
We use an OpenSSL toolkit to convert a PFX encoded certificate to PEM format. For testing this scenario, we use a password protected PFX-encoded file – certificatepfx.pfx and a 2048-bit RSA private key.
For exporting key:
openssl pkcs12 -in certificatepfx.pfx -nocerts -out privatekeyconvert.pem -nodes
Snippet of output
For exporting certificate
openssl pkcs12 -in certificatepfx.pfx -clcerts -nokeys -out certconvert.pem
Snippet of output
Note: Optionally, we can also have CA certificate chain as a part of the PFX file. In order to export it from the PFX file we run the following command:
openssl pkcs12 -in certificate.pfx -cacerts -nokeys -chain -out ca-chain.pem
Execute the following command to convert the data in the certificatepfx.pfx file to PEM format in the convertcert.pem file. The PEM file contains all of the certificates that were in the PFX file, and each of the certificates is wrapped within headers.
openssl pkcs12 -in certificatepfx.pfx -out convertcert.pem -nodes
Snippet of output
In order to use the certificate and private keys on another system in PEM format, you can convert the PFX file using the procedure mentioned above.
February 21, 2025
October 9, 2024