Monday 24 May 2021

disable ssl certificate validation on HttpsURLConnection

 Below snippet disables the SSL certificate validation on HttpsURLConnection.

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class SSLIgnoreCheck {

	static void disableCertValidation() throws NoSuchAlgorithmException, KeyManagementException {

		class HttpsTrustManager implements X509TrustManager {

			@Override
			public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

			}

			@Override
			public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

			}

			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return new X509Certificate[0];
			}
		}
		
		TrustManager[] trustAllCerts = new TrustManager[] { new HttpsTrustManager() };

		SSLContext sslContext = SSLContext.getInstance("SSL");
		sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

		HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

		// Create all-trusting host name verifier
		HostnameVerifier validHosts = new HostnameVerifier() {
			@Override
			public boolean verify(String arg0, SSLSession arg1) {
				return true;
			}
		};

		// All hosts will be valid
		HttpsURLConnection.setDefaultHostnameVerifier(validHosts);
	}
}




Previous                                                    Next                                                    Home

No comments:

Post a Comment