我正在寻找使用java 11 中提供的新 HttpClient。目前尚不清楚如何进行双向 TLS(2 路身份验证,客户端和服务器都提供证书。)
有人可以提供一个带有 HttpClient 的双向 TLS 示例吗?
我正在寻找使用java 11 中提供的新 HttpClient。目前尚不清楚如何进行双向 TLS(2 路身份验证,客户端和服务器都提供证书。)
有人可以提供一个带有 HttpClient 的双向 TLS 示例吗?
弄清楚了。创建一个 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();