Monday, October 10, 2005

Accessing HTTPS web services in Java

If any of you are receiving the following errors while trying to consume an external web service, read below for a solution.

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

This was done for/on Linux, but the process should be very similar for windows based clients.
  • Fetch certificate from server.
  • Cut and paste the certificate (including BEGIN and END lines)
    into a local file (ie; sitewithservice.pem).
  • Add certificate (ie; sitewithservice.pem) to local java keystore.
    • keytool -import -alias sitewithservice.com -keystore /opt/java/keystore -file sitewithservice.pem
    • NOTE: Answer "Yes" to "Trust this certificate? [no]:".

  • Add the following lines to your java web service client.

    • System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");

      java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

      System.setProperty("javax.net.ssl.trustStore",
      "[PATH TO YOUR KEYSTORE]");

      System.setProperty("javax.net.ssl.trustStorePassword",
      "[PASSWORD TO YOUR KEYSTORE]");
That is it!

Hope this helps someone.

-- ngeren