What is Java keytool?
The Java keytool is a command-line utility used to manage keystores in different formats containing keys and certificates. You can use the java keytool to import a certificate into a keystore. In many respects, the java keytool is a competing utility with openssl for keystore, key, and certificate management.
Use cases to import a certificate into a keystore.
You may want to import certificates into a keystore for two reasons:
- If you are using the keystore as a trust store, to add the first or an additional cert for your application to trust.
- To add a certificate response as a result of a Certificate Signing Request (CSR) signed by a third party Certification Authority (CA). See how to create a CSR.
What keytool command do I use to import a certificate into a keystore?
Use this command to import a certificate into a keystore using the java keytool. The result will be an updated keystore with an entry containing the imported certificate with the provided alias. Note that if the -file option is not provided, the certificate will be imported from stdin.
keytool -importcert \ -noprompt \ -alias example-import \ -file example.crt \ -keystore example.p12 \ -storepass changeit \ -storetype PKCS12 \ -v
Note that this is the java keytool importcert command. For more ways of importing certificates (crt) and keys into a keystore, read our post containing an example of the java keytool import command. Adding the -storepass flag to the importcert command will avoid the prompt.
To import certificate to cacerts, first find the path to the cacerts keystore in your installed JRE (Java Runtime Environment) and either copy it or navigate to the directory containing the cacerts keystore. Then run the above command to import a certificate, substituting the example.p12 name with cacerts: -keystore cacerts and changing the -storetype to JKS.
Java keytool options:
-noprompt – Do not prompt.
-alias – The alias of the entry encapsulated in the keystore. The chosen value should enhance the readability of the keystore entries, especially when the keystore contains multiple entries.
-file – The file containing the X.509 certificate being imported.
-keystore – The filename of the keystore.
-storepass – The current keystore password. We recommend leaving this option off and letting keytool prompt you instead of writing your password in plain text here.
-storetype – Recommended keystore types include PKCS12 and JKS. In this case, the keystore was of type PKCS12.
-v – Verbose output.
If you encounter Error: “java.lang.exception: Certificate reply does not contain public key for” it is likely you have either specified the wrong alias or the wrong keystore when importing the new cert to the existing private key entry.
Here are the official keytool docs to dive further into how to use the java keytool to import a certificate into a keystore.