Thursday, January 8, 2015

Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

If you use a self-signed certificate for a test,

you can encounter the following exception:

Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Download the certificate as follows:

http://izeye.blogspot.kr/2015/01/how-to-download-certificate-from-https.html

Copy the keystore not to compromise its integrity:

cp /Library/Java/JavaVirtualMachines/jdk1.8.0_05.jdk/Contents/Home/jre/lib/security/cacerts .

Import the downloaded certificate to the keystore:

keytool -import -alias test -keystore cacerts -file test.pem

Run a Java program with the following VM arguments:

-Djavax.net.ssl.trustStore=/Users/izeye/workspaces/openssl/java/cacerts -Djavax.net.ssl.trustStorePassword=changeit

You can also avoid the exception programmatically

by bypassing the certification validation as follows:

TrustManager[] trustManagers = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}

@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}

@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManagers, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

References:
http://stackoverflow.com/questions/6908948/java-sun-security-provider-certpath-suncertpathbuilderexception-unable-to-find
http://magicmonster.com/kb/prg/java/ssl/pkix_path_building_failed.html
http://www.nakov.com/blog/2009/07/16/disable-certificate-validation-in-java-ssl-connections/

No comments:

Post a Comment