2

As far as I know .pfx files are not required to contain both public and private key. However, I could not find a way how to create a file that contains only one of them.

I need this because I am writing a validator for .pfx files and I would like to check if the file contains both private and public key. For testing purposes I would like to create some invalid certificates.

Honza Brabec
  • 37,388
  • 4
  • 22
  • 30

3 Answers3

5

There may be a shorter way to do this without going through PEM, but I don't know it.

Extract the private key to PEM:

openssl.exe pkcs12 -in <pfx_file_name>.pfx -nocerts -out private_key.pem

Optional, if you don't want passwords in the PEM or PFX files:

openssl.exe rsa -in private_key.pem -out private_key.pem

Extract the public and private key to PEM:

openssl.exe pkcs12 -in <pfx_file_name>.pfx -out public_and_private_key.pem

Export the public key only to PFX:

openssl.exe pkcs12 -in public_and_private_key.pem -inkey private_key.pem -export -out public_key.pfx -nokeys

Export only the private key to PFX:

openssl.exe pkcs12 -in public_and_private_key.pem -inkey private_key.pem -export -out private_key.pfx -nocerts
Brian Gillespie
  • 3,213
  • 5
  • 27
  • 37
0

To extract the private key:

 Openssl.exe pkcs12 -in <pfx_file_name>.pfx -nocerts -out priv.pem

The generated private key file (priv.pem) will be password protected, to remove the pass phrase from the private key.

 Openssl.exe rsa -in priv.pem -out priv.pem

Next step is extracting the public key certificate from the pfx file, there is a direct command in OPENSSL to extract the public key certificate from the pfx file but the generated file will contain public key certificate and some other information. To extract only public key certificate first we need to convert the pfx file to pem which contains both private and public key, and then extract the public key certificate from this pem file:

 openssl.exe pkcs12 -in ClientCert1.pfx -out privpub.pem

The generated pem contains both private and public keys, use the following command to extract only the public key certificate:

 openssl x509 -inform pem -in privpub.pem -pubkey -out pub.pem -outform pem
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
  • 1
    I actually need it the other way round. I already have separate private and public keys. I need to create a .pfx certificate just from private key or just from public key. – Honza Brabec Sep 02 '14 at 17:06
0

If you're trying to create a single pfx file from a public/private key pair, then I think this question becomes a duplicate of this post.

openssl pkcs12 -inkey priv.pem -in pub.cert -export -out pfx_file.pfx

As it turns out, I don't have enough reputation to comment, otherwise I would have commented on your post, vice "answering."

Community
  • 1
  • 1
ice13berg
  • 713
  • 8
  • 12