Monday, April 28, 2014

Disabling certificate validation in Java

In case you need to disable validation of certificate here is Java snippet.
 import javax.net.ssl.*;  
 import java.security.SecureRandom;  
 import java.security.cert.X509Certificate;  
 public static void disableCertificateValidation() {  
  // Create a trust manager that does not validate certificate chains  
  TrustManager[] trustAllCerts = new TrustManager[] {   
  new X509TrustManager() {  
   public X509Certificate[] getAcceptedIssuers() {   
   return new X509Certificate[0];   
   }  
   public void checkClientTrusted(X509Certificate[] certs, String authType) {}  
   public void checkServerTrusted(X509Certificate[] certs, String authType) {}  
  }};  
  // Ignore differences between given hostname and certificate hostname  
  HostnameVerifier hv = new HostnameVerifier() {  
  public boolean verify(String hostname, SSLSession session) { return true; }  
  };  
  // Install the all-trusting trust manager  
  try {  
  SSLContext sc = SSLContext.getInstance("SSL");  
  sc.init(null, trustAllCerts, new SecureRandom());  
  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
  HttpsURLConnection.setDefaultHostnameVerifier(hv);  
  } catch (Exception e) {}  
 }  
I took code from here: Java client certificates over HTTPS/SSL

Related topics:
IBM Domino Java: No trusted certificate found. Fail?
Domino and No trusted certificate found
Disabling certificate validation in Java

2 comments :

grumpy_coder said...

Do you just run this method before making a connection ? Is calling this method all that is required in your agent ?

Dmytro said...

Yes I do. It helped that time.
I also remember we updated our certificate storage at Domino: http://dpastov.blogspot.dk/2014/01/domino-and-no-trusted-certificate-found.html
One more thing, make sure that the endpoint does not do any redirects to another place with wrong SSL.