gpt4 book ai didi

java - JDK11 HttpClient 双向 tls

转载 作者:行者123 更新时间:2023-12-04 22:35:08 25 4
gpt4 key购买 nike

我正在寻找使用 new HttpClient provided in java 11 .目前尚不清楚如何进行双向 TLS(2 路身份验证,客户端和服务器都提供证书。)
有人可以提供一个带有 HttpClient 的双向 TLS 示例吗?

最佳答案

弄清楚了。创建一个 HttpClient,然后传入 SSLContext 和 SSLParameters 对象。
将证书/ key 加载到 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();

关于java - JDK11 HttpClient 双向 tls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63022464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com