TransWikia.com

How to export CA certificate chain from PFX in PEM format without bag attributes

Unix & Linux Asked by BryKKan on January 7, 2021

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?

2 Answers

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>

Correct answer by BryKKan on January 7, 2021

Another solution without sed:

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

Answered by Rockallite on January 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP