Thursday, April 07, 2011

Java: Ignore/Trust an invalid SSL cert for https communication

Very Once a while you will need your Java app to talk to a pre prod server (Web Service) over https, but you face the issue is that SSL is not a valid/expired/self signed cert... 
You may get an error that looks like

org.springframework.web.client.ResourceAccessException: I/O error: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:453)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:401)

You can add code to your app to ignore it or you can ask java to ignore that server's bad cert... The following is how i get java to ignore that invalid cert.
How to Ignore/Trust a Single Cert

WINDOWS
"%JAVA_HOME%\bin\keytool" -import -keystore "%JAVA_HOME%\jre\lib\security\cacerts" -alias abc-dev -file abc-dev.cer

MAC
sudo $JAVA_HOME/bin/keytool -import -keystore $JAVA_HOME/lib/security/cacerts -alias abc-dev -file abc-dev.cer

CentOS/Linux 
sudo $JAVA_HOME/bin/keytool -import -keystore $JAVA_HOME/jre/lib/security/cacerts -alias abc-dev -file abc-dev.cer
How To Ignore/Trust a CA root certificate
--Note: there maybe multi files for a CA cert so do the following command for each file.

WINDOWS
"%JAVA_HOME%\bin\keytool" -import -trustcacerts -alias myCA -file myCA.cer.txt -keystore
"%JAVA_HOME%\jre\lib\security\cacerts"