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