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)
- 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
- 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