Skip to content

Instantly share code, notes, and snippets.

@guozi
Forked from paliwalarpan/SecureRestClient.java
Created March 28, 2022 13:21
Show Gist options
  • Save guozi/da9ad923c06c5947eb9351d397f7386b to your computer and use it in GitHub Desktop.
Save guozi/da9ad923c06c5947eb9351d397f7386b to your computer and use it in GitHub Desktop.
Two Way SSL Code
@Bean
public HttpClient httpClient(SSLContext sslContext) {
return HttpClients.custom()
.setMaxConnPerRoute(30)
.setMaxConnTotal(60)
.setSSLContext(sslContext).build();
}
@Bean
public ClientHttpRequestFactory clientHttpRequestFactory(HttpClient httpClient) {
return new HttpComponentsClientHttpRequestFactory(httpClient);
}
@Bean
public RestTemplate restOperations(ClientHttpRequestFactory clientHttpRequestFactory) throws Exception {
return new RestTemplate(clientHttpRequestFactory);
@Autowired
private ResourceLoader resourceLoader;
@Bean
public SSLContext sslContext() throws Exception {
//load the keystore file as input stream
InputStream keystoreStream = resourceLoader.getResource(keyStoreFile).getInputStream();
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
//get instance of keystore depends on type of store here we have //pkcs12
KeyStore keyStore = KeyStore.getInstance("PKCS12");
try {
keyStore.load(keystoreStream, keyStorePass.toCharArray());
} finally {
keystoreStream.close();
}
keyManagerFactory.init(keyStore, keyStorePass.toCharArray());
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
//load trust store file as input stream
KeyStore trustStore = KeyStore.getInstance("PKCS12");
InputStream truststoreSteam = resourceLoader.getResource(trustStoreFile).getInputStream();
try {
//load trust store
trustStore.load(truststoreSteam, trustStorePassword.toCharArray());
} finally {
truststoreSteam.close();
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
SSLContext sslcontext = SSLContext.getInstance("TLS");
//initialize ssl context with both key manager and trust manager
sslcontext.init(keyManagers, tmf.getTrustManagers(), null);
//return sslContext
return sslcontext;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment