Skip to content

Instantly share code, notes, and snippets.

@Gems
Created April 18, 2024 06:25
Show Gist options
  • Save Gems/93db2064b9bd5ea6f2f2d0bc387f6c5d to your computer and use it in GitHub Desktop.
Save Gems/93db2064b9bd5ea6f2f2d0bc387f6c5d to your computer and use it in GitHub Desktop.
HTTP Client Configurer with Default and System Store (cacerts) using io.github.hakky54:sslcontext-kickstart
import nl.altindag.ssl.SSLFactory; // io.github.hakky54:sslcontext-kickstart
@NoArgsConstructor
public class HttpClientConfigurerTrustAllCACerts implements HttpClientConfigurer {
@Override
@SneakyThrows
public void configureHttpClient(HttpClientBuilder clientBuilder) {
// val sslContext = SSLContexts.custom().loadTrustMaterial(null, (cert, authType) -> true).build();
// val x509TrustManager = getDefaultX509TrustManager();
// val sslContext = SSLContext.getInstance("TLS");
// val messageDigest = MessageDigest.getInstance("SHA-1");
// sslContext.init(new KeyManager[0], new TrustManager[] { new X509TrustManager() {
// @Override
// public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// x509TrustManager.checkClientTrusted(chain, authType);
// }
//
// @Override
// public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// x509TrustManager.checkServerTrusted(chain, authType);
// }
//
// @Override
// public X509Certificate[] getAcceptedIssuers() {
// return x509TrustManager.getAcceptedIssuers();
// }
// } }, new SecureRandom());
// sslContext.init(null, new TrustManager[] { getDefaultX509TrustManager() }, new SecureRandom());
val sslFactory = SSLFactory
.builder()
.withDefaultTrustMaterial()
.withSystemTrustMaterial()
.build();
val sslsf = new SSLConnectionSocketFactory(sslFactory.getSslContext(), new DefaultHostnameVerifier());
val socketFactoryRegistry =
RegistryBuilder.<ConnectionSocketFactory> create()
.register("https", sslsf)
.register("http", new PlainConnectionSocketFactory())
.build();
val connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
clientBuilder.setConnectionManager(connectionManager);
}
private static X509TrustManager getDefaultX509TrustManager() throws Exception {
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
for (val trustManager : trustManagerFactory.getTrustManagers())
if (trustManager instanceof X509TrustManager)
return (X509TrustManager) trustManager;
throw new Exception("No X509 trust manager found.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment