Wednesday, January 23, 2008

Trust All Certificates

Need to establish an Https connection and don't care about validating the server's unsigned certificate? Don't want to mess with importing the server's certificate into a local keystore? This won't show you how to ignore those SSLHandshakeExceptions due to unsigned certs, but it will show you how to get rid of them all together!

Step 1:


Implement the X509TrustManager Interface as follows.

public class TrustEverythingTrustManager implements 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) { }
}


Step 2:


Implement the HostnameVerifier Interface as follows.

public class VerifyEverythingHostnameVerifier implements HostnameVerifier {

public boolean verify(String string, SSLSession sslSession) {
return true;
}
}


Step 3:


Initialize an SSLContext with your TrustEverythingTrustManager and set the context as the default SSL socket factory on the HttpsURLConnection class.

TrustManager[] trustManager = new TrustManager[] {new TrustEverythingTrustManager()};

// Let us create the factory where we can set some parameters for the connection
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManager, new java.security.SecureRandom());
} catch (NoSuchAlgorithmException e) {
// do nothing
}catch (KeyManagementException e) {
// do nothing
}

HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());


Step 4:


Open the connection and set your VerifyEverythingHostnameVerifier as the HostnameVerifier.

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new VerifyEverythingHostnameVerifier());



Thats it. Done and Done!

3 comments:

mjremijan said...

Thanks for the post. I remember doing this years ago but of course forgot how to implement it. Short and sweet and to the point and it works!

Kamlesh said...

Thanks! It helped...

Best Ragards,
Kamlesh
http://www.kamleshkumar.com

Andrew Lindzon said...

How do I turn this into an executable or a .java program?