Java KeyStore - keytool commands
These commands can be used with the Java JRE6/JDK6 "keytool" command
Generate a key pair (none signed)
keytool -genkeypair -keyalg RSA -alias MyC13Cert -keysize 2048 -keystore MyKeyStoreFile.jks \
-dname "cn=www.code13.com, ou=C13OU, o=C13O, c=GB" -validity 365
Generate a CSR
keytool -certreq -alias MyC13Cert -keystore MyKeyStoreFile.jks -file MyCsrFile.csr
List contents of the keystore
These commands list the contents of the keystore.
keytool -list -keystore MyKeyStoreFile.jks -storepass MyStorePassword -rfc
keytool -list -keystore MyKeyStoreFile.jks -storepass MyStorePassword -v
The "-v" option instructs the keytool command to list the certificates in human-readable format, the "-rfc" option lists the certificates in printable encoding format.
Exporting the public certs
keytool -exportcert -alias MyC13Cert -file MyPublicCert.cer -keystore MyKeyStoreFile.jks -storepass MyStorePassword -rfc
keytool -exportcert -alias MyC13Cert -file MyPublicCert.cer -keystore MyKeyStoreFile.jks -storepass MyStorePassword -v
Signing (used an External CA file) – Open SSL
openssl x509 -req -in MyCsrFile.csr \
-CA MyCaPublicCert.cer -CAkey MyCaPrivateKey.key -CAcreateserial \
-out MyPublicSignedCert.cer -days 365
Importing the CSR (CA first)
keytool -importcert -trustcacerts -file MyCaPublicCert.cer -keystore MyKeyStoreFile.jks
keytool -importcert -alias MyC13Cert -file MyPublicCert.cer -keystore MyKeyStoreFile.jks
Importing a private key to a JKS from a PKCS12
keytool -importkeystore \
-deststorepass MyStorePassword -destkeypass MyKeyPassword -destkeystore MyKeyStoreFile.jks \
-srckeystore MyPKCS12KeyStoreFile.p12 -srcstoretype PKCS12 -srcstorepass MyStoreAndKeyPassword -alias 1
Extracting a private key from a Java-KeyStore
It is not possible to directly extract the private key from a JKS without using custom Java code; however the JKS can be "imported" into a new PKCS12-keystore from which the private keys & public certificates can be extracted.
The following keytool command does the "import" to the PKCS12 keystore:
keytool -importkeystore -srckeystore MyKeyStoreFile.jks \
-destkeystore MyPKCS12KeyStoreFile.p12 -deststoretype PKCS12
The following OPENSSL command can be used to export the data, the exported file can be opened to get the printable encoded data.
openssl pkcs12 -in MyPKCS12KeyStoreFile.p12 -out MyKeysAndCerts.pem -nodes