忽略 Servlet 中的 SSL 证书

Ignore SSL Certificate in a Servlet

我遇到以下异常:

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

我做了一些研究并更改了我的连接代码:

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();

到目前为止,这解决了问题,我不再收到异常并且连接正常。

当我在 Tomcat 中的 Servlet 运行 中使用相同的代码时,问题再次出现。

为什么?

试试下面的代码。

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());
}

网站证书是由private/company-owned CA颁发的还是自签的?

... new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() ...
  • Trustore 为空:
    您是否尝试加载包含可信 CA 及其链的 keystore/file?
  • isTrusted 始终返回 "true":
    您正在覆盖标准 JSSE 证书验证过程并信任所有过程,因此根本没有安全性。
  • 该异常:表示证书验证失败。 RootCA,或整个 CA 链丢失。

看来 Tomcat 忽略了您的 SSLContext。像那样使用,无论如何 sslContext 都是无用的。调试结果? JVM SSL设置?异常堆栈跟踪?

您已经开发了一个servlet。正确的?它只是一个网页。如果您想要启用 SSL 的网页,那么您必须在安装该证书后购买 SSL 证书。如果您没有该证书,请使用上述代码。上述代码适用于所有安全问题。

您必须从 Verisign 和 Thawte 等公司购买 SSL/TSL 证书。