Import PKCS12 private keys into JKS keystores using Java Keytool
This is very simple yet when I googled around I saw erratic answers such as ‘it is not possible’ or ‘you have to write java code’.
As a matter of fact, keytool (a key management utility shipped in Sun’s JDK) lets you do it simply.
- What do you want to do?
Convert alice.p12 to alice.jks - Why do you want to do that?
In Metro, a WS stack, it is common to use JKS as a format for storing private keys - How do you convert then?
See below
Keytool’s documentation refers to the following option
-importkeystore [-v]
[-srckeystore ] [-destkeystore ]
[-srcstoretype ] [-deststoretype ]
[-srcstorepass ] [-deststorepass ]
[-srcprotected] [-destprotected]
[-srcprovidername ]
[-destprovidername ]
[-srcalias [-destalias ]
[-srckeypass ] [-destkeypass ]]
[-noprompt]
[-providerclass
[-providerarg ]] ...
[-providerpath
]
So in fact in our case, converting from alice.p12 to alice.jks is extremely simple:
- Create an empty JKS store
keytool -genkey -alias alice -keystore alice.jks keytool -delete -alias alice -keystore alice.jks
- Import alice.p12 into alice.jks
keytool -v -importkeystore -srckeystore alice.p12 -srcstoretype PKCS12 -destkeystore truststore.jks -deststoretype JKS
Couldn’t this be done with just one command:
keytool -importkeystore -srckeystore alice.p12 -srcstoretype PKCS12 -destkeystore alice.jks
keytool will create alice.jks if it doesn’t already exist.