Wednesday 25 February 2015

An SSL Truster

Should you wish, when testing say, to trust all ssl certificates:


import java.net.URL;

import javax.net.ssl.*;

import com.mediagraft.shared.utils.UtilsHandbag;

/**
 * Modify the JVM wide SSL trusting so that locally signed https urls, and others, are
 * no longer rejected.
 *
 * Use with care as the JVM should not be used in production after activation.
 *
 */
public class JvmSslTruster {

  private static boolean activated_;

  private static X509TrustManager allTrustingManager_ = new X509TrustManager() {

    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
      return null;
    }

    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
    }

    public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
    }
  };

  public static SSLSocketFactory trustingSSLFactory() {
    SSLContext sc = null;
    try {
      sc = SSLContext.getInstance("SSL");
      sc.init(null, new TrustManager[]{allTrustingManager_}, new java.security.SecureRandom());
      new URL(UtilsHandbag.getSecureApplicationURL()); //Force loading of installed trust manager
    }
    catch (Exception e) {
      throw new RuntimeException("Unhandled exception", e);
    }
    return sc.getSocketFactory();
  }

  public static void startTrusting() {
    if (!activated_) {
      HttpsURLConnection.setDefaultSSLSocketFactory(trustingSSLFactory());
      com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(trustingSSLFactory());
      activated_ = true;
    }
  }

  private JvmSslTruster() {
  }
}

No comments:

Post a Comment