Java Keytool
The keytool command is a key and certificate management utility.
KeyStore vs TrustStore
We use keystore and truststore when our application need to use SSL/TLS. The default format for keystore and truststore is JKS until Java 8. Starting with Java 9, the default format is now PKCS12, which is language-neutral way to store encrypted private keys and certificates.
A Java Keystore stores private keys, certificates with public keys used for SSL/TLS.
Truststore is the opposite of keystore. It stores certificates that identifies others.
Java has a default truststore with path $JAVA_HOME/jre/lib/security/cacerts. The initial password for cacerts is changeit. (notice it doesn’t have a .jks or .pkcs12 extension)
Generate KeyStore and Keypair
To generate a keystore and keypair. You need to provide information here. the keystore and domain both require password.
1 | keytool -genkey -alias mydomain -keyalg RSA -keystore keystore.jks -keysize 2048 |
This will generate keystore.jks file. its alias is ‘mydomain’.
use keytool -list
command to view keystore entry. or use keytool -list -v
for verbose output. You will be prompted for the keystore password.
1 | $ keytool -list -keystore keystore.jks |
Generate CSR from KeyStore
To generate a Certificate Signing Request(CSR) for an existing Java keystore. You will be prompted for the keystore password.
1 | keytool -certreq -alias mydomain -keystore keystore.jks -file mydomain.csr |
This will generate mydomain.csr
Create a self-signed Certificate
1 | keytool -genkey -keyalg RSA -alias selfsigned -keystore selfsigned.jks -validity 360 -keysize 2048 |
This will generate selfsigned.jks. use keytool -list
to view the certificate
Export the certificate. you will be prompted for the keystore password. This will generate the certificate in DER encoded format.
1 | keytool -exportcert -alias selfsigned -file selfsigned.der -keystore selfsigned.jks |
To convert DER to PEM
1 | openssl x509 -inform der -in selfsigned.der -out selfsigned.crt |
Import a Certificate to TrustStore
To import a CA or intermedia certificate to an existing java trusted keystore.
1 | $ cd $JAVA_HOME |
You will be prompted for the keystore password
To Examine Default TrustStore at $JAVA_HOME/jre/lib/security/cacerts.
1 | $ cd $JAVA_HOME/jre/lib/security |
You can see here there are 134 trusted certificates.
Reference