【问题标题】:Java not using truststoreJava 不使用信任库
【发布时间】:2021-01-11 12:17:43
【问题描述】:

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

需要注意的几点:

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

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

  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,但运气不佳。

我现在可以克服上述错误的唯一方法是使用信任所有证书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());

【问题讨论】:

标签: java ssl java-8 ssl-certificate truststore


【解决方案1】:

您需要将其安装为受信任的服务器。如果它是由不受信任的 CA 签名的,您还必须安装 CA 的证书。

【讨论】:

  • 我该怎么做?我对服务器没有任何影响,我只能写客户端。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-14
    • 2019-02-26
    • 2014-08-24
    • 2016-04-18
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多