Wednesday, June 15, 2011

How to solve javax.net.ssl.SSLHandshakeException?

A few days ago, I deployed one of my applications to Weblogic 10.3 AS but it failed to send emails, I was using gmail as my SMTP server and this was the error :

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.

After many searches I found the solution and now I'm gonna share it with you.
The problem is that the public key of the SMTP server is not imported into JRE's default keystore, in order to import it, you should follow these steps:
  1. Install OpenSSL (http://www.openssl.org/)
  2. Double-click the openssl file from the directory that gets installed
  3. Run: s_client -connect smtp.gmail.com:465 (465 is port of SMTP, if you are using another port, use that one)
  4. From the output, you want only the alphanumeric string between the lines which say 'BEGIN CERTIFICATE' and 'END CERTIFICATE' (inclusive). Copy the results into a file called gmail.cert using your favorite text editor.

  5. Now its time to import the public key into default keystore. From Java installation's bin directory run:
    keytool -import -alias smtp.gmail.com -keystore $JAVA_HOME/jre/lib/security/cacerts -file C:\path\to\gmail.cert
* The default keystore password is 'changeit'.

This should solve your problem, if you still have problem with Weblogic server, the reason is that Weblogic has it's own default keystore which is located at: 

$ORACLE_HOME/weblogic/wlserver_10.3/server/lib/DemoTrust.jks

All you need to do is to import gmail.cert into the above keystore in the same way you did for JRE's keystore.

* The default keystore password is 'DemoTrustKeyStorePassPhrase'.