PKCS#12

PKCS#12 defines an archive file format for storing several cryptography objects (e.g. a certificate, and intermediate certificate and a private key) as a single file (often referred to as a "keystore"). Files in this format usually end with a .pfx or .p12 suffix.

Create

The command below creates a keystore (/tomcat/.keystore) and generates a key pair which will be stored in it...

keytool -genkeypair -alias tomcat -keyalg RSA -keystore /tomcat/.keystore.p12 -storetype pkcs12


You will be prompted for:
  • a password, which you should note securely
  • your first and last name (CN)
  • your Organizational Unit (OU) - normally your department name
  • your Organization (O)
  • your City or Locality (L)
  • your State or Province (ST)
  • your two letter country code (C)

Enter 'yes' to confirm your entries.The key password can be the same as the keystore password.

View

For Tomcat example created above...

keytool -list -keystore /tomcat/.keystore.p12

Using openssl instead of keytool...

openssl pkcs12 -info -in cert.pfx

You are likely to be asked for a password and passphrase

Delete

For Tomcat example created above...

keytool -delete -keystore /tomcat/.keystore -alias tomcat

To remove the entire keystore (are you sure you want to do that?) then simply delete it using your OS delete command...

rm /tomcat/.keystore

Load

openssl pkcs12 -export -out cert.pfx -inkey privateKey.pem -in cert1.pem -certfile cert2.pem

Convert

To convert a PFX file to a PEM file that contains both the certificate and private key...

openssl pkcs12 -in cert.pfx -out cert.pem -nodes

Extract

To extract the private key from a PFX file to a PEM file...

openssl pkcs12 -in cert.pfx -nocerts -out privateKey.pem

To extract the certificate only...

openssl pkcs12 -in cert.pfx -clcerts -nokeys -out cert.pem

To remove the password from an extracted private key:

openssl rsa -in privateKey.pem -out privateKey1.pem