Java: Overriding function to disable SSL certificate check

后端 未结 3 737
刺人心
刺人心 2020-11-29 01:02

The web service is rest over SSL and it has self signed certificate, hosted in remote system.I have already created a client accessing that web service. This is done by addi

3条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 01:45

    This should be sufficient. I use this when testing code against testing and staging servers where we don't have properly signed certificates. However, you should really really strongly consider getting a valid SSL certificate on your production server. Nobody wants to be wiretapped and have their privacy violated.

    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, new TrustManager[] { new TrustAllX509TrustManager() }, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
        public boolean verify(String string,SSLSession ssls) {
            return true;
        }
    });
    

    And this.

    import javax.net.ssl.X509TrustManager;
    import java.security.cert.X509Certificate;
    
    /**
     * DO NOT USE IN PRODUCTION!!!!
     * 
     * This class will simply trust everything that comes along.
     * 
     * @author frank
     *
     */
    public class TrustAllX509TrustManager implements X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs,
                String authType) {
        }
    
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
                String authType) {
        }
    
    }
    

    Best of luck!

    ===UPDATE===

    I just wanted to point out that there's a service called Let's Encrypt which automates the process of generating and setting up SSL/TLS certificates recognised by virtually everybody, and it's absolutely free!

提交回复
热议问题