How to bypass ssl certificate checking in java

前端 未结 4 1861
忘掉有多难
忘掉有多难 2020-11-30 05:50

I want access a SOAP webservice url having https hosted in a remote vm. I am getting an exception while accessing it using HttpURLConnection.

Here\'s my code:

<
相关标签:
4条回答
  • 2020-11-30 06:36

    Instead of using HttpsURLConnection.setDefaultSSLSocketFactory and your own implementation of TrustManager or X509ExtendedTrustManager, you can use TrustManagerFactory with a KeyStore with the certificate that issued the certificate you need to trust (for a self-signed certificate, this is the same as the host certificate) and call HttpsURLConnection.setSSLSocketFactory on the specific instance. This is both less code and avoids the security problems with trusting all HTTPS certicates.

    In main:

                if (url.getProtocol().toLowerCase().equals("https")) {
                    HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                    https.setSSLSocketFactory(createSSLSocketFactory());
                    http = https;
                }
    

    The method createSSLSocketFactory looks like this:

        private static SSLSocketFactory createSSLSocketFactory() {
             File crtFile = new File("server.crt");
             Certificate certificate =          CertificateFactory.getInstance("X.509").generateCertificate(new FileInputStream(crtFile));
    
             KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
             keyStore.load(null, null);
             keyStore.setCertificateEntry("server", certificate);
    
             TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
             trustManagerFactory.init(keyStore);
    
             SSLContext sslContext = SSLContext.getInstance("TLS");
             sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    
             return sslContext.getSocketFactory();
        }
    
    0 讨论(0)
  • 2020-11-30 06:42

    Edit : Understand the vulnerability this would cause before using it. This is by no means recommended for production use.

    The best way is to create a dummy trustmanager that trusts everything.

     TrustManager[] dummyTrustManager = new TrustManager[] { new X509TrustManager() {
          public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
          }
    
          public void checkClientTrusted(X509Certificate[] certs, String authType) {
          }
    
          public void checkServerTrusted(X509Certificate[] certs, String authType) {
          }
        } };
    

    Then use the dummy trustmanager to initialize the SSL Context

    SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, dummyTrustManager, new java.security.SecureRandom());
    

    Finally use the SSLContext to open connection

    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    
        URL url = new URL("https://myhost:8913/myservice/service?wsdl");
    

    This question has already been answered here in more detail Java: Overriding function to disable SSL certificate check

    Update:

    Above issue is due to certificate signature algorithm not being supported by Java. As per this post, later releases of Java 8 have disabled md5 algorithm.

    To enable md5 support, locate java.security file under <jre_home>/lib/security and locate the line (535)

    jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024, 
    

    and remove MD5

    0 讨论(0)
  • 2020-11-30 06:42

    Try with Apache HTTP client, this works for me.

    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustStrategy() {
         public boolean isTrusted(final X509Certificate[] chain, String authType) throws CertificateException {
              return true;
         }
    });
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
    
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    
    // GET or POST request with the client
    ...
    
    0 讨论(0)
  • 2020-11-30 06:52

    Using X509ExtendedTrustManager instead of X509TrustManager() solved the problem. Here's the example:

    public void trustAllHosts()
        {
            try
            {
                TrustManager[] trustAllCerts = new TrustManager[]{
                        new X509ExtendedTrustManager()
                        {
                            @Override
                            public java.security.cert.X509Certificate[] getAcceptedIssuers()
                            {
                                return null;
                            }
    
                            @Override
                            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
                            {
                            }
    
                            @Override
                            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
                            {
                            }
    
                            @Override
                            public void checkClientTrusted(java.security.cert.X509Certificate[] xcs, String string, Socket socket) throws CertificateException
                            {
    
                            }
    
                            @Override
                            public void checkServerTrusted(java.security.cert.X509Certificate[] xcs, String string, Socket socket) throws CertificateException
                            {
    
                            }
    
                            @Override
                            public void checkClientTrusted(java.security.cert.X509Certificate[] xcs, String string, SSLEngine ssle) throws CertificateException
                            {
    
                            }
    
                            @Override
                            public void checkServerTrusted(java.security.cert.X509Certificate[] xcs, String string, SSLEngine ssle) throws CertificateException
                            {
    
                            }
    
                        }
                };
    
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    
                // Create all-trusting host name verifier
                HostnameVerifier allHostsValid = new  HostnameVerifier()
                {
                    @Override
                    public boolean verify(String hostname, SSLSession session)
                    {
                        return true;
                    }
                };
                // Install the all-trusting host verifier
                HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            }
            catch (Exception e)
            {
                log.error("Error occurred",e);
            }
        }
    
    0 讨论(0)
提交回复
热议问题