PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/ConfigurableRestSource/configurable-rest-source/src/main/java/com/davis/ddf/crs/client/TrustingOkHttpClient.java

https://gitlab.com/samuel-davis/DDF-TestSource
Java | 175 lines | 143 code | 23 blank | 9 comment | 9 complexity | be7b9d5eb24f2c8152f48723d9f3dfc7 MD5 | raw file
  1. package com.davis.ddf.crs.client;
  2. import org.apache.commons.io.FileUtils;
  3. import org.apache.commons.io.IOUtils;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import java.io.File;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.OutputStream;
  11. import java.security.KeyStore;
  12. import java.security.KeyStoreException;
  13. import java.security.NoSuchAlgorithmException;
  14. import java.security.cert.CertificateException;
  15. import java.util.concurrent.TimeUnit;
  16. import javax.net.ssl.HostnameVerifier;
  17. import javax.net.ssl.KeyManager;
  18. import javax.net.ssl.KeyManagerFactory;
  19. import javax.net.ssl.SSLContext;
  20. import javax.net.ssl.SSLSession;
  21. import javax.net.ssl.SSLSocketFactory;
  22. import javax.net.ssl.TrustManager;
  23. import javax.net.ssl.X509TrustManager;
  24. import okhttp3.OkHttpClient;
  25. /** Created by Samuel Davis on 7/26/16. */
  26. public class TrustingOkHttpClient {
  27. private static final Logger logger =
  28. LoggerFactory.getLogger(TrustingOkHttpClient.class.getName());
  29. private OkHttpClient client;
  30. public TrustingOkHttpClient() {}
  31. public OkHttpClient getUnsafeOkHttpClient(
  32. int readTimeout, int connectTimeout, String clientCertPath, String certPassword) {
  33. try {
  34. // Create a trust manager that does not validate certificate chains
  35. final TrustManager[] trustAllCerts =
  36. new TrustManager[] {
  37. new X509TrustManager() {
  38. @Override
  39. public void checkClientTrusted(
  40. java.security.cert.X509Certificate[] chain, String authType)
  41. throws CertificateException {}
  42. @Override
  43. public void checkServerTrusted(
  44. java.security.cert.X509Certificate[] chain, String authType)
  45. throws CertificateException {}
  46. @Override
  47. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  48. return new java.security.cert.X509Certificate[] {};
  49. }
  50. }
  51. };
  52. KeyStore keyStore = null;
  53. if (clientCertPath == null || certPassword == null) {
  54. clientCertPath = "certs/embedded.p12";
  55. logger.info(
  56. "Client cert path or password were null creating keystore from jar resources {}",
  57. clientCertPath);
  58. certPassword = "changeit";
  59. keyStore = readKeyStoreJarResources(clientCertPath, certPassword);
  60. } else {
  61. logger.info("Creating Keystore for Client Cert Path of {}", clientCertPath);
  62. keyStore = readKeyStore(clientCertPath, certPassword);
  63. }
  64. // Install the all-trusting trust manager
  65. KeyManagerFactory kmf =
  66. KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  67. kmf.init(keyStore, certPassword.toCharArray());
  68. KeyManager[] keyManagers = kmf.getKeyManagers();
  69. final SSLContext sslContext = SSLContext.getInstance("TLS");
  70. //added a Key manager authenticate the Client.
  71. sslContext.init(keyManagers, trustAllCerts, new java.security.SecureRandom());
  72. // Create an ssl socket factory with our all-trusting manager
  73. final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
  74. OkHttpClient.Builder builder = new OkHttpClient.Builder();
  75. builder.sslSocketFactory(sslSocketFactory);
  76. HostnameVerifier hostnameVerifier =
  77. new HostnameVerifier() {
  78. @Override
  79. public boolean verify(String hostname, SSLSession session) {
  80. return true;
  81. }
  82. };
  83. builder.hostnameVerifier(hostnameVerifier);
  84. builder.connectTimeout(connectTimeout, TimeUnit.SECONDS);
  85. builder.readTimeout(readTimeout, TimeUnit.SECONDS);
  86. logger.info("Successfully created UnsafeOkHttpClient");
  87. client = builder.build();
  88. return client;
  89. } catch (Exception e) {
  90. logger.error("Exception creating trusting okhttp client {}", e);
  91. throw new RuntimeException(e);
  92. }
  93. }
  94. private KeyStore readKeyStoreJarResources(String keyStorePath, String clientCertPassword) {
  95. KeyStore ks = null;
  96. InputStream in = null;
  97. try {
  98. ks = KeyStore.getInstance("PKCS12");
  99. logger.info("Successfully got instance of keystore PKCS12");
  100. //ks = KeyStore.getInstance(KeyStore.getDefaultType());
  101. // get user password and file input stream
  102. in = TrustingOkHttpClient.class.getClassLoader().getResourceAsStream(keyStorePath);
  103. OutputStream outputStream = new FileOutputStream("deploy/embedded.p12");
  104. IOUtils.copy(in, outputStream);
  105. in.close();
  106. outputStream.close();
  107. in=null;
  108. in = FileUtils.openInputStream(new File("deploy/embedded.p12"));
  109. logger.info("Successfully read client certificate from JAR resources ");
  110. char[] password = clientCertPassword.toCharArray();
  111. ks.load(in, password);
  112. } catch (KeyStoreException | NoSuchAlgorithmException | IOException | CertificateException e) {
  113. e.printStackTrace();
  114. } finally {
  115. if (in != null) {
  116. try {
  117. in.close();
  118. } catch (IOException e) {
  119. logger.error("Error loading certificate {}", e);
  120. }
  121. }
  122. }
  123. return ks;
  124. }
  125. private KeyStore readKeyStore(String keyStorePath, String clientCertPassword) {
  126. KeyStore ks = null;
  127. InputStream in = null;
  128. try {
  129. ks = KeyStore.getInstance("PKCS12");
  130. logger.info("Successfully got instance of keystore PKCS12");
  131. //ks = KeyStore.getInstance(KeyStore.getDefaultType());
  132. // get user password and file input stream
  133. logger.info("Loading client certificate from path of {}", keyStorePath);
  134. File initialFile = new File(keyStorePath);
  135. in = FileUtils.openInputStream(initialFile);
  136. logger.info("Successfully read client certificate from absolute path and input stream. ");
  137. char[] password = clientCertPassword.toCharArray();
  138. ks.load(in, password);
  139. } catch (KeyStoreException | NoSuchAlgorithmException | IOException | CertificateException e) {
  140. e.printStackTrace();
  141. } finally {
  142. if (in != null) {
  143. try {
  144. in.close();
  145. } catch (IOException e) {
  146. logger.error("Error loading certificate {}", e);
  147. }
  148. }
  149. }
  150. return ks;
  151. }
  152. }