пʼятниця, 16 вересня 2011 р.

Avoid SSLException with all-trusting TrustManager

Anyone who stumbled upon SSL in their day-to-day Java joy, know that by default Java is very picky about certificates on the other end. Whether you want to submit a HTTP request to the site with expired certificate (yes, people change them, and they may forget to do that) or happen to work against an endpoint with self-signed certificate (not everyone are ready to blindly give hundreds of bucks for those expensive bits), you'll be kindly refused (if SSLException can be described as kind)

In such cases you should find some way around the issue to make things work.Whenever its about the remote service, I preferred to maintain a separate truststore for the project, but having a headache of keystores during development is a motivation killer.

Here is how you can avoid JVM to check peer certificates for validity. The below code will accept any SSL certificate presented, this means - no security unless you know what you're doing. Generally this property switch will be of great use at development time or debugging time.

import java.security.cert.X509Certificate;

// ...

if ("true".equalsIgnoreCase(System.getProperty("trust.ignore", "true"))) {
	TrustManager[] trustAllCerts = new TrustManager[]{
		new X509TrustManager() {
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
			public void checkClientTrusted(
				X509Certificate[] certs, String authType) {
			}
			public void checkServerTrusted(
				X509Certificate[] certs, String authType) {
			}
			public boolean isClientTrusted( X509Certificate[] cert) {
				return true;
			}
			public boolean isServerTrusted( X509Certificate[] cert) {
				return true;
			}
		}
	};

	// 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) {
	}
}

1 коментар:

  1. Found another post on the issue with similar solution: http://exampledepot.com/egs/javax.net.ssl/TrustAll.html

    ВідповістиВидалити