mercoledì 10 novembre 2010

Accept all SSL certificate (self signed certificate) in Java applications

When a java application tries to connect to a https service, the jvm check the server's certificate in order to test its validity. If you are using a self-signed certificate this maybe a problem. There are at least three way to go beyond this problem but, IMHO, I think the use of this class is the easiest way:

 import java.security.KeyManagementException;  
 import java.security.NoSuchAlgorithmException;  
 import java.security.cert.X509Certificate;  
 import javax.net.ssl.HostnameVerifier;  
 import javax.net.ssl.HttpsURLConnection;  
 import javax.net.ssl.SSLContext;  
 import javax.net.ssl.SSLSession;  
 import javax.net.ssl.TrustManager;  
 import javax.net.ssl.X509TrustManager;  
 public class UnTrustManager {  
      public static void acceptAllCertificates() throws NoSuchAlgorithmException, KeyManagementException {  
           TrustManager[] trustAllCerts = new TrustManager[1];  
           trustAllCerts[0] = new innerUnTrustManager();  
           SSLContext sc = SSLContext.getInstance("SSL");  
           sc.init(null, trustAllCerts, null);  
           HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
           HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {  
                public boolean verify(String hostname, SSLSession session) {  
                     return true;  
                }  
           });  
      }  
      public static class innerUnTrustManager implements TrustManager, X509TrustManager {  
           public X509Certificate[] getAcceptedIssuers() {  
                return null;  
           }  
           public void checkServerTrusted(X509Certificate[] certs, String authType)  
                     throws java.security.cert.CertificateException {  
           }  
           public void checkClientTrusted(X509Certificate[] certs, String authType)  
                     throws java.security.cert.CertificateException {  
           }  
      }  
 }  

Nessun commento: