Java Keytool essential commands

Deshan Kalupahana
2 min readMay 3, 2018

--

Java keytool is a default application which comes with jre. It can be used to manage digital key pairs and certificates.

Keystore in keytool stores the these keys and certificates. This keystore is just a file and user can generate any number of keystores for his usage. Keystore has a password for limit the access to it. Keystore can keep the private key and its certificate. Each key as an alias to recognize it. So different keys and certificates can be added to the keystore with different alias.

A certificate can be generate for a key in keystore. The certificate needed to be signed by a trusted certificate authority. So a CSR needed to be generate from the public key and it shoud be provide for trusted certificate authority to generate the certificate file. If its a testing or internal system that is trusted, a certificate can be directly generate from the Keytool.

  • Create keypair with a keystore
    $ keytool -genkey -alias userdomain -keyalg RSA -keystore keystore.jks -keysize 1024
  • Import CA certificate to a key store
    $ keytool -import -trustcacerts -alias userdomain -file certificate.crt -keystore keystore.jks
  • Generate self signed certificate
    $ keytool -genkey -keyalg RSA -alias userdomain -keystore keystore.jks -storepass password -validity 360 -keysize 1024
  • Check the certficates in a keystore
    $ keytool -list -v -keystore keystore.jks
  • Check the certificate state
    $ keytool -printcert -v -file certificate.crt
  • Export certificate from a keystore
    $ keytool -export -alias userdomain -file certificate.crt -keystore keystore.jks
  • Import a certificate into java trustedstore
    $ keytool -import -trustcacerts -file /path/to/ca/cert.pem -keystore $JAVA_HOME/jre/lib/security/cacerts -alias trusted_alias

Originally published at http://deshankalupahana.wordpress.com on May 3, 2018.

--

--