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          
30          System.setProperty("jdk.internal.httpclient.disableHostnameVerification", "true");
31          
32          // Create a trust manager that does not validate certificate chains
33          // and ignore exception PKIX path building failed: unable to find valid certification path to requested target
34          var trustAllCerts = new TrustManager[] {
35                  
36              new X509TrustManager() {
37                  
38                  @Override
39                  public X509Certificate[] getAcceptedIssuers() {
40                      return new X509Certificate[0];
41                  }
42  
43                  @SuppressWarnings("java:S4830")
44                  @Override
45                  public void checkClientTrusted(X509Certificate[] certs, String authType) {
46                      // nothing
47                  }
48  
49                  @SuppressWarnings("java:S4830")
50                  @Override
51                  public void checkServerTrusted(X509Certificate[] certs, String authType) {
52                      // nothing
53                  }
54              }
55          };
56          
57          try {
58              this.sslContext = SSLContext.getInstance("TLSv1.2");
59              this.sslContext.init(null, trustAllCerts, new SecureRandom());
60              
61          } catch (NoSuchAlgorithmException | KeyManagementException e) {
62              LOGGER.log(
63                  LogLevelUtil.CONSOLE_ERROR,
64                  "Error ignoring untrusted SSL",
65                  e
66              );
67          }
68      }
69      
70      public SSLContext getSslContext() {
71          return this.sslContext;
72      }
73  }