如何使用Apache HttpClient处理无效的SSL证书?

2022-08-31 08:23:26

我知道,关于这个问题有很多不同的问题和很多答案......但我无法理解...

我有: ubuntu-9.10-desktop-amd64 + NetBeans6.7.1 从关闭“安装”按原样。我需要通过HTTPS连接到某个网站。为此,我使用Apache的HttpClient。

从教程我读到:

“一旦你正确安装了JSSE,通过SSL的安全HTTP通信应该像
普通的HTTP通信一样简单。举几个例子:

HttpClient httpclient = new HttpClient();
GetMethod httpget = new GetMethod("https://www.verisign.com/"); 
try { 
  httpclient.executeMethod(httpget);
  System.out.println(httpget.getStatusLine());
} finally {
  httpget.releaseConnection();
}

到现在为止,我写这个:

HttpClient client = new HttpClient();

HttpMethod get = new GetMethod("https://mms.nw.ru");
//get.setDoAuthentication(true);

try {
    int status = client.executeMethod(get);
    System.out.println(status);

    BufferedInputStream is = new BufferedInputStream(get.getResponseBodyAsStream());
    int r=0;byte[] buf = new byte[10];
    while((r = is.read(buf)) > 0) {
        System.out.write(buf,0,r);
    }

} catch(Exception ex) {
    ex.printStackTrace();
}

结果我有一组错误:

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
        at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
        at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1627)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:204)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:198)
        at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:994)
        at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:142)
        at sun.security.ssl.Handshaker.processLoop(Handshaker.java:533)
        at sun.security.ssl.Handshaker.process_record(Handshaker.java:471)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:904)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1132)
        at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:643)
        at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:78)
        at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
        at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
        at org.apache.commons.httpclient.HttpConnection.flushRequestOutputStream(HttpConnection.java:828)
        at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2116)
        at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
        at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
        at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
        at simpleapachehttp.Main.main(Main.java:41)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:302)
        at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:205)
        at sun.security.validator.Validator.validate(Validator.java:235)
        at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:147)
        at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:230)
        at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:270)
        at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:973)
        ... 17 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:191)
        at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:255)
        at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:297)
        ... 23 more

我需要做些什么来创建最简单的SSL连接?(可能没有KeyManager和Trust Manager等。


答案 1

https://mms.nw.ru 使用不在缺省信任管理器集中的自签名证书。要解决此问题,请执行下列操作之一:

  • 使用接受任何证书的 配置(见下文)。SSLContextTrustManager
  • 使用包含证书的相应信任库进行配置。SSLContext
  • 将该站点的证书添加到缺省 Java 信任存储区。

下面是一个程序,它创建一个(大多毫无价值的)SSL上下文,接受任何证书:

import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class SSLTest {
    
    public static void main(String [] args) throws Exception {
        // configure the SSLContext with a TrustManager
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
        SSLContext.setDefault(ctx);

        URL url = new URL("https://mms.nw.ru");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        System.out.println(conn.getResponseCode());
        conn.disconnect();
    }
    
    private static class DefaultTrustManager implements X509TrustManager {

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

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

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }
}

答案 2

https://mms.nw.ru 可能使用不是由证书颁发机构颁发的证书。因此,您需要将证书添加到受信任的 Java 密钥存储区,如无法找到到请求目标的有效证书路径中所述:

当使用在 https 协议中运行的启用了 SSL 的服务器的客户端上工作时,如果服务器证书不是由证书颁发机构颁发的,而是由私有 CMS 颁发的,则可能会收到错误“无法找到所请求目标的有效证书路径”。

不要惊慌。您需要做的就是将服务器证书添加到受信任的 Java 密钥库(如果您的客户端是用 Java 编写的)。您可能想知道如何无法访问安装服务器的计算机。有一个简单的程序可以帮助你。请下载 Java 程序并运行

% java InstallCert _web_site_hostname_

此程序打开与指定主机的连接并启动 SSL 握手。它打印了所发生错误的异常堆栈跟踪,并向您显示服务器使用的证书。现在,它会提示您将证书添加到受信任的密钥库。

如果您改变了主意,请输入“q”。如果您确实要添加证书,请输入“1”或其他数字以添加其他证书,甚至是CA证书,但您通常不想这样做。做出选择后,程序将显示完整的证书,然后将其添加到当前目录中名为“jssecacerts”的Java KeyStore中。

要在程序中使用它,请将 JSSE 配置为将其用作信任库,或将其复制到$JAVA_HOME/jre/lib/security 目录中。如果希望所有 Java 应用程序都将证书识别为受信任的证书,而不仅仅是 JSSE,则还可以覆盖该目录中的 cacerts 文件。

完成所有这些之后,JSSE将能够完成与主机的握手,您可以通过再次运行程序来验证。

要获取更多详细信息,您可以查看Leeland的博客不再“无法找到请求目标的有效认证路径”