Saturday, 5 October 2013

Java Keytool command usage


In a Client-Server Model when Server is exposing resources (like WebService, Servlets, etc) on HTTPS, the Java client program needs to authenticate the Server certificate to access the resource. I tried to explain the usage of few basic Keytool commands which are handy in such situations.


Java 7 (JDK or JRE)

Command Usage

  • First you need to obtain the Server certificate, you can do via hitting the resource URL in a Web Browser. Your Web Browser will ask to authenticate the Server and trust the certificate, once you do that, you will see a small icon on Address URL (either on left of right side of the URL), you can click the icon and it will provide you options to export the certificate.
  • Export the certificate in a .pem or .crt format and copy it to directory: <JAVA/JRE_HOME>/jre/lib/security and switch to this directory.
  • Command to import certificate into Java's truststore
    • keytool -import -file <PEM or CRT file you copied> -keystore cacerts
      • The cacerts truststore password is changeit 
Now the Java Client program should be able to access the server resource over https. Following are few additional commands which you might find useful:
  • Command to see available certificates in Java's truststore
    • keytool -list -keystore cacerts
  • Command to delete an existing certificate from Java's truststore
    • keytool -delete -alias <certificate alais name> -keystore cacerts
  • Command to change the alias name of an existing certificate from Java's truststore (this command is useful when you have more than one certificates but with same alias)
    • keytool -changealias -alias <existing-alias-name> -destalias <new-alias-name> -keystore cacerts
  • You can also export a certificate stored in a keystore via following command
    • keytool -export -file <exporeted-cert-filename.crt> -alias <alias-name-of-cert-which-to-be-exported> -keystore cacerts
Please note that all above commands are valid for any keystore (not only Java's own cacerts trustore); in that case you just put your keystore name instead of cacerts. Generally this is required when your application is maintaining its own keystore.