views:

905

answers:

3

How to bypass invalid SSL certificate errors with Apache HttpClient 4.0?

+1  A: 

Here's a solution for 3.x, which should be modifiable to 4.x.

Stefan Kendall
+3  A: 

You need to create a SSLContext with your own TrustManager and create HTTPS scheme using this context. Here is the code,

SSLContext sslContext = SSLContext.getInstance("SSL");

// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                    System.out.println("getAcceptedIssuers =============");
                    return null;
            }

            public void checkClientTrusted(X509Certificate[] certs,
                            String authType) {
                    System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs,
                            String authType) {
                    System.out.println("checkServerTrusted =============");
            }
} }, new SecureRandom());

SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
Scheme httpsScheme = new Scheme("https", sf, 443);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);

HttpParams params = new BasicHttpParams();
ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
HttpClient              httpClient = new DefaultHttpClient(cm, params);
ZZ Coder
Say I don't want to buy valid SSL certificate for my site and just want to use it, this piece of code can help? How come I don't see any part where a URL is needed or exception handling is needed?
Viet
As you can see the X509TrustManager doesn't check for anything and doesn't throw any exceptions so any cert is accepted.
ZZ Coder
Just use anonymous DH ciphersuites and be done with it.
GregS
Thanks! It was simpler than I expected :)
Viet
+1  A: 

in extension to this answer it will be nice to override the hostnameverifier

// ...
SSLSocketFactory sf = new SSLSocketFactory (sslContext);
sf.setHostnameVerifier(new X509HostnameVerifier() {

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

  public void verify(String host, String[] cns, String[] subjectAlts)
  throws SSLException {
  }

  public void verify(String host, X509Certificate cert) throws SSLException {
  }

  public void verify(String host, SSLSocket ssl) throws IOException {
  }
});
// ...
eldur