Skip to content

Instantly share code, notes, and snippets.

@mcmoe
Last active February 15, 2024 08:24
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mcmoe/19d377f4a95db71ac3e9bd5524044e34 to your computer and use it in GitHub Desktop.
Save mcmoe/19d377f4a95db71ac3e9bd5524044e34 to your computer and use it in GitHub Desktop.
Creating a keystore and truststore using the Java keytool plus useful check and modification keytool commands

Creating a keystore and exporting its certificate into a new truststore

Create the Keystore and generate a certificate, an example is shown below:

keytool -genkey -alias client -keyalg RSA -keystore client.jks -keysize 2048

Export a certificate from a Keystore:

keytool -export -alias client -file client.crt -keystore client.jks

Import the certificate to a Truststore:

keytool -import -v -trustcacerts -alias client -file client.crt -keystore clienttrust.jks


Java Keytool Commands for Checking

Check a stand-alone certificate:

keytool -printcert -v -file mydomain.crt

Check which certificates are in a Java Keystore:

keytool -list -v -keystore keystore.jks

Check a particular Keystore entry using an alias:

keytool -list -v -keystore keystore.jks -alias mydomain


Other Java Keytool Commands

Delete a certificate from a keystore:

keytool -delete -alias mydomain -keystore keystore.jks

Change a keystore password:

keytool -storepasswd -new new_storepass -keystore keystore.jks

List Java trusted CA Certs:

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

Import new CA into Java trusted Certs:

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


Based on source

For more info on certificates check here.


The stores can be changed using:

System.setProperty("javax.net.ssl.keyStore", "keystore.jks");
System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "changeit");

or:

-Djavax.net.ssl.keyStore=path/to/keystore.jks
-Djavax.net.ssl.trustStore=cacerts.jks"
-Djavax.net.ssl.keyStorePassword=changeit
@mcmoe
Copy link
Author

mcmoe commented Aug 8, 2018

To extract certificates from a website:

openssl s_client -showcerts -connect example.com:443 </dev/null 2>/dev/null|openssl x509 -outform DER >example.crt

These can then be imported into a trust store

@loic-roux-404
Copy link

loic-roux-404 commented Oct 8, 2021

To extract certificates from a website:

openssl s_client -showcerts -connect example.com:443 </dev/null 2>/dev/null|openssl x509 -outform DER >example.crt

These can then be imported into a trust store

This isn't working on last ubuntu, here another solution

echo -n | openssl s_client -connect url:443 | openssl x509 -out /tmp/cert.crt

@mcmoe
Copy link
Author

mcmoe commented Jan 18, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment