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

What is PKCS #12?
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.
What is a PFX file?
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.
What is a PEM file?
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
How to convert PFX file to PEM format?
Scenario 1: Export private key and certificate files from PFX file
The following procedure will convert the PFX-encoded certificate file into two files in PEM format.
- certconvert.pem – PEM file containing the SSL/TLS certificate for the resource.
- privatekeyconvert.pem – PEM file containing the private key of the certificate with no password protection.
Prerequisites
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.
Commands
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
Scenario 2: Convert PFX file to PEM format
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.
Command
openssl pkcs12 -in certificatepfx.pfx -out convertcert.pem -nodes
Snippet of output
Conclusion
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.