Java 不使用信任库

问题描述

我正在为 Java 中的 REST API 创建 HTTPS 客户端,但有些问题我无法很好地解决

注意事项:

  1. 服务器正在使用自签名证书(可能在某些环境中,客户可能会使用受信任的机构对其进行签名)

  2. 我已从服务器下载根证书并使用 truststore 命令添加keytool

  3. 我将系统属性设置为 System.setProperty("javax.net.ssl.trustStore",path);

  4. 我可以列出服务器证书以验证它是否正确导入并可供我的客户端使用,例如:

    String filename = path_to_truststore;
    FileInputStream is = new FileInputStream(filename);
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    String password = "changeit";
    keystore.load(is,password.tochararray());
    
    // This class retrieves the most-trusted CAs from the keystore
    PKIXParameters params = new PKIXParameters(keystore);
    
    // Get the set of trust anchors,which contain the most-trusted CA certificates
    Iterator it = params.getTrustAnchors().iterator();
    while (it.hasNext()) {
        TrustAnchor ta = (TrustAnchor) it.next();
        // Get certificate
        X509Certificate cert = ta.getTrustedCert();
        if (cert.getIssuerDN().getName().contains(server_cert_CN)) {
            System.out.println(cert.toString());
        }
    }
    
  5. 服务器证书在备用主题名称中没有 IP 地址,因此我使用自定义 HostnameVerifier 来缓解该问题,该问题工作正常

之后,我正在创建一个 URL 对象并获得如下连接:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

但我一直收到错误

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

我尝试使用自己的信任存储。我曾尝试从信任库创建我自己的 SSLSocketFactory,但没有成功。

我现在可以克服上述错误的唯一方法是使用我非常想避免的 Trust all 证书 TrustManager

我还尝试使用属性从 SSL 等获取一些调试级别的日志记录:

System.setProperty("javax.net.debug","ssl,handshake,trustmanager");

但是除了上面的异常之外,我没有得到任何输出

欢迎任何帮助或想法。我使用的是 Java 1.8

更新

我用于根据 Felix 的请求创建 SSLContext 的代码

private SSLContext getSSLContext(File certificatePath) throws CertificateException,NoSuchAlgorithmException,KeyStoreException,KeyManagementException,IOException {
        if (sslContext == null) {
            InputStream inputStream = new FileInputStream(certificatePath);

            X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(inputStream);

            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null,null);
            keyStore.setCertificateEntry(Integer.toString(1),certificate);

            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);

            SSLContext context = SSLContext.getInstance("TLS");

            context.init(null,trustManagerFactory.getTrustManagers(),null);  
            
            // Setting the context above with create TrustManager does not work. 
            // An accept all trust manager as below works.
            // context.init(null,getSelfSignedTrustManager(),null);

            sslContext = context;
        }
        return sslContext;
    }

后来,我在创建任何连接之前设置了上下文,例如:

HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

解决方法

根据GitHub repo in my comment中显示的文件,我选择了相关部分并在下面显示。此示例使用您创建的 SslContext 并将其设置为客户端。

HttpClient client = HttpClient.newBuilder()      // Type java.net.http.HttpClient
        .version(HttpClient.Version.HTTP_1_1)    // Change to needed HTTP version
        .sslContext(getSSLContext(filePath))     // Function from above
        .build();

String[] headerArray = {
        "Accept","text/html","User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
                "AppleWebKit/537.36 (KHTML,like Gecko) Chrome/86.0.4240.183 " + 
                "Safari/537.36"};                // Extend header if needed

HttpRequest request = HttpRequest.newBuilder()   // Type java.net.http.HttpRequest
        .uri(uri)                                // URI of type java.net.URI
        .headers(headerArray)
        .GET()
        .build();

HttpResponse<String> response = null;            // Type java.net.http.HttpResponse
try {
    response = client.send(request,HttpResponse.BodyHandlers.ofString());
} catch (InterruptedException e) {
    e.printStackTrace();
}