解决PKIX问题:unable to find valid certification path to requested target【X509TrustManager】

2014年11月份曾经调研过关于PKIX问题,当时总结的方案为,通过一个JAVA类InstallCert去生成一个名为jssecacerts的证书,将名为jssecacerts的证书拷贝\\%JAVA_HONME%\\jre\\lib\\security\\目录中,每次进行上述操作都需要重启对应的tomcat服务,无形间给这种对应方式带来了一些工作量。
最近,又在网上看了许多关于类似PKIX问题的文章,发现了一种通过X509TrustManager绕过https认证的一种方式,拿了几个网站做例子,果然可以实现!
下面为实现的方式:
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.X509Certificate;
/**
 * How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException
 */
public class HttpsUtil {
	/**
	 * 此方法可以绕过安全访问所需要的证书
	 * @param httpsUrl 安全请求页面地址
	 * @return
	 * @throws Exception
	 */
	public static URLConnection detourHttps(String httpsUrl)throws Exception{
		/*
		 * fix for Exception in thread "main"
		 * 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
		 */
		TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}

			public void checkClientTrusted(X509Certificate[] certs,
					String authType) {
			}

			public void checkServerTrusted(X509Certificate[] certs,
					String authType) {
			}

			@Override
			public void checkClientTrusted(
					java.security.cert.X509Certificate[] arg0, String arg1)
					throws CertificateException {
			}

			@Override
			public void checkServerTrusted(
					java.security.cert.X509Certificate[] arg0, String arg1)
					throws CertificateException {
			}
		} };

		SSLContext sc = SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, new java.security.SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

		// Create all-trusting host name verifier
		HostnameVerifier allHostsValid = new HostnameVerifier() {
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		};

		// Install the all-trusting host verifier
		HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);	
		URL url = new URL(httpsUrl);
		URLConnection con = url.openConnection();
		return con;
	}
}


你可能感兴趣的:(TO,https,find,valid,Unable,PKIX,https认证)