JDK11 HttpClient 双向 tls

问题描述 投票:0回答:2

我希望使用 java 11 中提供的 新 HttpClient 。目前尚不清楚如何进行双向 TLS(双向身份验证,客户端和服务器都提供证书。)

有人可以提供一个使用 HttpClient 进行双向 TLS 的示例吗?

java ssl java-11 java-http-client
2个回答
16
投票

想通了。创建一个 HttpClient,然后传入 SSLContext 和 SSLParameters 对象。

将证书/密钥加载到 SSLContext 中:

 // cert+key data. assuming X509 pem format
final byte[] publicData = your_cert_data; // -----BEGIN CERTIFICATE----- ...
final byte[] privateData = your_key_data; // -----BEGIN PRIVATE KEY----- ...

// parse certificate
final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
final Collection<? extends Certificate> chain = certificateFactory.generateCertificates(
        new ByteArrayInputStream(publicData));

LOG.info("Successfully loaded the client cert certificate chain {}", String.join(" -> ", chain
        .stream()
        .map(certificate -> {
            if (certificate instanceof X509Certificate) {
                final X509Certificate x509Cert = (X509Certificate) certificate;
                return x509Cert.getSubjectDN().toString();
            } else {
                return certificate.getType();
            }
        }).collect(Collectors.toList())));

// parse key
final Key key = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateData));

// place cert+key into KeyStore
KeyStore clientKeyStore = KeyStore.getInstance("jks");
final char[] pwdChars = KEYSTORE_PASSWORD.toCharArray(); // use a random string, like from java.security.SecureRandom
clientKeyStore.load(null, null);
clientKeyStore.setKeyEntry(YOUR_SERVICE_NAME, key, pwdChars, chain.toArray(new Certificate[0]));

// initialize KeyManagerFactory
KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance("SunX509");
keyMgrFactory.init(clientKeyStore, pwdChars);

// populate SSLContext with key manager
SSLContext sslCtx = SSLContext.getInstance("TLSv1.2");
sslCtx.init(keyMgrFactory.getKeyManagers(), null, null);

创建ssl参数,将needClientAuth设置为true:

SSLParameters sslParam = new SSLParameters();
sslParam.setNeedClientAuth(true);

最后,创建HttpClient:

HttpClient client = HttpClient.newBuilder()
    .sslContext(sslCtx)
    .sslParameters(sslParam)
    .build();

0
投票

' 行final Key key = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateData));不适用于 X.509 编码密钥,该密钥在此片段的第一行中假定。 '

更换:

final byte[] privateData = your_key_data; // -----BEGIN PRIVATE KEY----- ...

作者:

final String privateDataString = "-----BEGIN PRIVATE KEY-----\n[...]\n-----END PRIVATE KEY-----"
final byte[] privateData = Base64.getDecoder().decode(privateDataString.replaceAll("-----BEGIN PRIVATE KEY-----", "").replaceAll("-----END PRIVATE KEY-----", "").replaceAll("\\n", ""));
© www.soinside.com 2019 - 2024. All rights reserved.