Accept or Ignore Self Signed Certificates While reading ssl web page using Java

Turns out this is quite easy to do but hard to find the code for it. So here it is.

TrustManager[] trustAllCerts = 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) {
	}
} };

// Install the all-trusting trust manager
SSLContext sc;
try {
	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() {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	};
	HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (Exception e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

So basically what the above manager does is that it creates a socketFactory with a trust manager which allows all certificates and sets that as the default socket factory. The 2nd part is to validate a hostname which is not really important unless you are working on a server side IMO.

Tags: , , , ,

One Response to “Accept or Ignore Self Signed Certificates While reading ssl web page using Java”

  1. Mike Carrington Says:

    This was really helpful, thanks for posting🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: