View Javadoc
1   package com.jsql.util;
2   
3   import org.apache.logging.log4j.LogManager;
4   import org.apache.logging.log4j.Logger;
5   
6   import javax.net.ssl.SSLContext;
7   import javax.net.ssl.TrustManager;
8   import javax.net.ssl.X509TrustManager;
9   import java.security.KeyManagementException;
10  import java.security.NoSuchAlgorithmException;
11  import java.security.SecureRandom;
12  import java.security.cert.X509Certificate;
13  
14  /**
15   * SSL certificates are used by https connection. This utility class
16   * gets rid of malformed certification chains from bad configured websites
17   * in order to ignore connection exception in that specific case.
18   */
19  public class CertificateUtil {
20      
21      /**
22       * Log4j logger sent to view.
23       */
24      private static final Logger LOGGER = LogManager.getRootLogger();
25      
26      private SSLContext sslContext = null;
27  
28      public CertificateUtil() {
29          System.setProperty("jdk.internal.httpclient.disableHostnameVerification", "true");
30          
31          // Create a trust manager that does not validate certificate chains
32          // and ignore exception PKIX path building failed: unable to find valid certification path to requested target
33          var trustAllCerts = new TrustManager[] {
34              new X509TrustManager() {
35                  @Override
36                  public X509Certificate[] getAcceptedIssuers() {
37                      return new X509Certificate[0];
38                  }
39                  @SuppressWarnings("java:S4830")
40                  @Override
41                  public void checkClientTrusted(X509Certificate[] certs, String authType) {
42                      // nothing
43                  }
44                  @SuppressWarnings("java:S4830")
45                  @Override
46                  public void checkServerTrusted(X509Certificate[] certs, String authType) {
47                      // nothing
48                  }
49              }
50          };
51          
52          try {
53              this.sslContext = SSLContext.getInstance("TLSv1.2");
54              this.sslContext.init(null, trustAllCerts, new SecureRandom());
55          } catch (NoSuchAlgorithmException | KeyManagementException e) {
56              LOGGER.log(LogLevelUtil.CONSOLE_ERROR, "Error ignoring untrusted SSL", e);
57          }
58      }
59      
60      public SSLContext getSslContext() {
61          return this.sslContext;
62      }
63  }