1

I have the following code which conditionally (based on a boolean) disables SSL certificate checking.

However, if I set the boolean to false and re-run my code, the SSL checking still seems to be disabled (when it should be re-enabled).

So, what's the opposite logic of this, so that checking is restored?

if (bIgnoreSSL) {
  TrustManager[] trustAllCertificates = new TrustManager[] {
    new X509TrustManager()
    {
      @Override
      public X509Certificate[] getAcceptedIssuers() { return null; // Not relevant.}

      @Override
      public void checkClientTrusted(X509Certificate[] certs, String authType) { // Do nothing. Just allow them all. }

      @Override
      public void checkServerTrusted(X509Certificate[] certs, String authType){ // Do nothing. Just allow them all.}
    }
  };

   HostnameVerifier trustAllHostnames = new HostnameVerifier()
   {
        @Override
        public boolean verify(String hostname, SSLSession session) { return true; // Just allow them all. }
   };

        try
        {
            System.setProperty("jsse.enableSNIExtension", "false");
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCertificates, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
        }
        catch (GeneralSecurityException e)
        {
            throw new ExceptionInInitializerError(e);
        }
}
else {
  // Code to restore here (Opposite of above?)
}
Jim Taylor
  • 111
  • 2
  • 10

1 Answers1

1

One alternative is to first save the defaults in a variable, so you can restore them later:

// save defaults (do this before setting another defaults)
HostnameVerifier defaultVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
SSLSocketFactory defaultFactory = HttpsURLConnection.getDefaultSSLSocketFactory();

if (bIgnoreSSL) {
...
} else {
    // restore defaults
    HttpsURLConnection.setDefaultHostnameVerifier(defaultVerifier);
    HttpsURLConnection.setDefaultSSLSocketFactory(defaultFactory);
}

Another alternative (a better one, IMO) is to not set the default for all connections, but set for each individual connection instead:

HttpsURLConnection conn = // create connection

if (bIgnoreSSL) {
    // set custom verifier and factory only for this connection
    conn.setHostnameVerifier(trustAllHostnames);
    conn.setSSLSocketFactory(sc.getSocketFactory());
}
// no need to restore (else), as I didn't change the defaults

This changes the verifier and factory only for the specified connection, without affecting the defaults (so there's no need to restore).