I have a PKCS12 file containing the full certificate chain and private key. I need to break it up into 3 files for an application. The 3 files I need are as follows (in PEM format):

  • an unecrypted key file
  • a client certificate file
  • a CA certificate file (root and all intermediate)

This is a common task I have to perform, so I'm looking for a way to do this without any manual editing of the output.

I tried the following:

openssl pkcs12 -in <filename.pfx> -nocerts -nodes -out <clientcert.key>
openssl pkcs12 -in <filename.pfx> -clcerts -nokeys -out <clientcert.cer>
openssl pkcs12 -in <filename.pfx> -cacerts -nokeys -chain -out <cacerts.cer>

This works fine, however, the output contains bag attributes, which the application doesn't know how to handle.

After some searching I found a suggested solution of passing the results through x509 to strip the bag attributes.

openssl x509 -in <clientcert.cer> -out <clientcert.cer>

This works, but I run into an issue on the cacert file. The output file only contains one of the 3 certs in the chain.

Is there a way to avoid including the bag attributes in the output of the pkcs12 command, or a way to have the x509 command output include all the certificates? Additionally, if running it through x509 is the simplest solution, is there a way to pipe the output from pkcs12 into x509 instead of writing out the file twice?

up vote 15 down vote accepted

The solution I finally came to was to pipe it through sed.

openssl pkcs12 -in <filename.pfx> -nocerts -nodes | sed -ne '/-BEGIN PRIVATE KEY-/,/-END PRIVATE KEY-/p' > <clientcert.key>
openssl pkcs12 -in <filename.pfx> -clcerts -nokeys | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <clientcert.cer>
openssl pkcs12 -in <filename.pfx> -cacerts -nokeys -chain | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <cacerts.cer>

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.