I am getting the following exception:
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
I did some research and changed my connection code this:
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
CloseableHttpClient client = HttpClients.custom()
.setRedirectStrategy(new LaxRedirectStrategy())
.setSslcontext(sslContext)
.setConnectionManager(connMgr)
.build();
This fixed the problem so far, I am no longer getting the exception and the connection works.
The problem arises again when I use the same code in a Servlet running in Tomcat.
Why ?
If the SSL certificate is not validates as trusted or does not match the target host, an HTTPS and other SSL encrypted connection cannot be established and all attempts will result in SSLHandshakeException or IOException.
Try the following code.
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class DummyX509TrustManager implements X509TrustManager {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
throws CertificateException {
}
};
final TrustManager[] trustAllCerts = new TrustManager[] { new DummyX509TrustManager() };
try {
SSLContext sslContext= SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, null);
CloseableHttpClient client = HttpClients.custom()
.setRedirectStrategy(new LaxRedirectStrategy())
.setSslcontext(sslContext)
.setConnectionManager(connMgr)
.build();
} catch (KeyManagementException e) {
throw new IOException(e.getMessage());
} catch (NoSuchAlgorithmException e) {
throw new IOException(e.getMessage());
}
Is the website certificate issued by a private/company-owned CA or is it a self-signed?
... new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() ...
So it seems like Tomcat ignored your SSLContext. Used like that, the sslContext is useless anyway. Debugging results? JVM SSL settings? Exception stack trace?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With