Java 11 Apache HTTPClient SSL 证书身份验证不起作用

标签 java ssl httpclient apache-httpclient-4.x

我正在使用以下代码的修改版本进行 SSL 客户端证书身份验证。它在 JDK 8 中工作,最近我更改为 JDK 11,现在相同的代码身份验证失败。如果我切换到 JDK 8,它就可以工作。 JDK 11 中处理 SSL 客户端证书身份验证的任何更改?使此代码在 JDK 中运行的任何提示都会有所帮助。

package org.example.test;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import javax.net.ssl.SSLContext;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;

/**
 * Demonstrate connecting to a server secured with client-side SSL certificates.
 */
public class ConnectIT {

    /**
     * Path to your client-side SSL certificate in the PKCS12 format, as generated by OpenSSL.
     */
    final String KEY_STORE_PATH = "/path/to/pkcs12file.p12";

    /**
     * PKCS12 file passphrase.
     */
    final String KEY_STORE_PASSWORD = "correct horse battery staple";

    /**
     * URL to connect to. That is, a server for which the above certificate is required.
     */
    final String URL = "https://secure.example.org";

    @Test
    public void sslConnect() throws KeyStoreException, IOException, CertificateException,
            NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException {

        // Load the key store, containing the client-side certificate.
        KeyStore keyStore = KeyStore.getInstance("pkcs12");
        InputStream keyStoreInput = new FileInputStream(KEY_STORE_PATH);
        keyStore.load(keyStoreInput, KEY_STORE_PASSWORD.toCharArray());
        System.out.println("Key store has " + keyStore.size() + " keys");

        // Create an SSL context with our private key store.
        // We are only loading the key-material here, but if your server uses a self-signed certificate,
        // you will need to load the trust-material (a JKS key-store containing the server's public SSL
        // certificate) as well.
        SSLContext sslContext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD.toCharArray())
                .useTLS()
                .build();

        // Prepare the HTTPClient.
        HttpClientBuilder builder = HttpClientBuilder.create();
        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(
                sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        builder.setSSLSocketFactory(sslConnectionFactory);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory)
                .register("http", new PlainConnectionSocketFactory())
                .build();
        HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
        builder.setConnectionManager(ccm);

        // Perform a sample HTTP request.
        try (CloseableHttpClient httpClient = builder.build()) {
            HttpGet httpget = new HttpGet(URL);
            try (CloseableHttpResponse response = httpClient.execute(httpget)) {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    System.out.println("Response content length: " + entity.getContentLength());
                    System.out.printf(EntityUtils.toString(entity));
                }
                EntityUtils.consume(entity);
            }
        }
    }
}

谢谢

最佳答案

JRE 11 不是问题,但它默认使用的 TLSv1.3 是问题。 Apache HttpClient 5.0 已经过与 JRE 11 TLSv1.3 的兼容性测试,但 HttpClient 4.5 还没有。现在只需强制使用 TLSv1.2,问题应该就会消失。

关于Java 11 Apache HTTPClient SSL 证书身份验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53843843/

相关文章:

java - 从 Web 链接访问 .jnlp 文件时出错

Java 安全架构

java - 如何在不使用 JGit 下载到本地系统的情况下获取所有提交?

ssl - 支持 phantomjs 中的 SSL 客户端身份验证

python - pip 无法与 pypi 服务器建立安全连接

c# - HttpClient 在上传前读取整个文件。 UWP

java - JMock 模拟对象可以返回另一个模拟对象吗?

ruby-on-rails - 我必须为 Heroku 上的自定义域 SSL 付费才能摆脱警告标志,对吧?

android - 连接池关闭android

java - 除非我显式传递内容长度,否则使用 InputStreamEntity 通过 httpclient 构建 http put 请求将不起作用