5

I'm trying to get Java to accept all certs over HTTPS. This is for testing purposes. Before I was getting a cert not found error. However, after adding the following code before my code I get a HTTPS hostname wrong: should be <sub.domain.com> error. The problem is my url IS that url. How do I get around this issue? The below is the code I've added to attempt to fix the problem..

        // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[]{
        new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
            }
        }
    };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }
Skizit
  • 43,506
  • 91
  • 209
  • 269

1 Answers1

9

You need to set the a HostNameVarifier also Ex:

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

public class TrustAllHostNameVerifier implements HostnameVerifier {

    public boolean verify(String hostname, SSLSession session) {
        return true;
    }

}

Then

 httpsConnection.setHostnameVerifier(new TrustAllHostNameVerifier ());
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 2
    just a heads up. this can lead to MTM attacks , the certificate is not being verified by a trusted CA in this case.SSL is not secure unless at least one peer is authenticated. – Tito Oct 08 '13 at 05:48
  • 1
    True, but the OP specifically stated that the need was for testing purposes – John Rix Jul 03 '14 at 12:17