Extracting Public And Private Keys From A Java Key Store

9 February 2025

Step 1: Creating the “public-private” key-pair.    

keytool -genkey -alias client -validity 365 -keystore keystore.jks 

Step 2: Validate the “public-private” key pair.
keytool -list -v -keystore keystore.jks

Step 3: Extract the “public key” from the “public-private”
keytool -export -alias client -keystore keystore.jks -rfc -file public.cert

Step 4: Check the extracted public key (public.cert)
type public.cert

Step 5: Time to create the truststore using the public key, which was extracted.
keytool -import -alias client -file public.cert -keystore server.truststore 
keytool -list -v -keystore server.truststore

Steps Private Keys Export : It is required to save the private key in the PKCS#12 format 

and we can convert that to a text file using openssl:
Step 1: keytool -v -importkeystore -srckeystore keystore.jks -srcalias client -destkeystoremyp12file.p12 -deststoretype PKCS12
Step 2: openssl pkcs12 -in myp12file.p12 -out private.pem

Other Keytool Commands:

- keytool -delete -alias client -keystore keystore.jks

- keytool -storepasswd -new new_storepass -keystore keystore.jks

- keytool -list -v -keystore $JAVA_HOME/jre/lib/security/cacerts

- Import New CA into Trusted Certs

keytool -import -trustcacerts -file /path/to/ca/ca.pem -alias CA_ALIAS -keystore $JAVA_HOME/jre/lib/security/cacerts

Frequently used OpenSSL Commands:

http://shib.kuleuven.be/docs/ssl_commands.shtml

Tags