解决 https 证书验证不通过的问题

解决的办法:忽略服务端和客户端的证书校验即可。java 提供的相关的类。

通过重写TrustManager的checkClientTrusted(检查客户端证书信任)和checkServerTrusted(检查服务端证书验证)。以及HostnameVerifier的verify(校验)方法即可取消对证书的所有验证。

import javax.net.ssl.*;
import java.io.IOException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class DisableSSLCertificate {
    private static final Logger LOGGER = LoggerFactory.getLogger(DisableSSLCertificateCheckUtil.class);
    private DisableSSLCertificate() {
    }
    public void disableChecks() {
        try {
            new URL("https://0.0.0.0/").getContent();
        } catch (IOException e) {
            // This invocation will always fail, but it will register the
            // default SSL provider to the URL class.
        }
        try {
            SSLContext sslc;
            sslc = SSLContext.getInstance("TLS");
            TrustManager[] trustManagerArray = {new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }};
            sslc.init(null, trustManagerArray, null);
            HttpsURLConnection.setDefaultSSLSocketFactory(sslc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        } catch (Exception e) {
            LOGGER.error("error msg:{}", e);
            throw new IllegalArgumentException("证书校验异常!");
        }
    }
}

影响的范围:将会影响整个tomcat里面对证书的验证。即通过tomcat里面的其他项目虽然没有执行这一段代码但是也同样会忽略证书的验证。

影响的时间:执行这段代码之后的所有时间都生效。

 

posted @ 2017-04-26 12:16  wade&luffy  阅读(2657)  评论(1编辑  收藏  举报