Friday, October 21, 2011

HTTPS without certificate validation check

By default Java validates certificates when you do HTTPS queries. If it is not needed (for test environments, for example), it is possible to disable it (even it is much more complicated then it should be). Just add this code somewhere during initialization (this is groovy, so sorry some formatting):


  import javax.net.ssl.*
  import java.security.cert.*

  javax.net.ssl.TrustManager tm = new javax.net.ssl.X509TrustManager() {
    public boolean isClientTrusted(X509Certificate[] chain) { return true; }
    public boolean isHostTrusted(X509Certificate[] chain) { return true; }
    public boolean isServerTrusted(X509Certificate[] chain) { return true; }
    public X509Certificate[] getAcceptedIssuers() { return null; }
    public void checkClientTrusted(X509Certificate[] chain, String s){  }
    public void checkServerTrusted(X509Certificate[] chain, String s) {  }
  }
  HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) { return true; }
  }
  TrustManager[] trustAllCerts = new TrustManager[1];
  trustAllCerts[0] = tm;
  SSLContext sc = SSLContext.getInstance("SSL");
  sc.init(null, trustAllCerts, new java.security.SecureRandom());
  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  HttpsURLConnection.setDefaultHostnameVerifier(hv);



No comments:

Post a Comment