HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Security / Bypass SSL Certificate Checking in Java

Bypass SSL Certificate Checking in Java

To disable or bypass SSL certificate checking is never a recommended solution for SSL issues, but at test environment – sometimes you may need this. In this tutorial, I am creating instances of org.apache.http.impl.client.DefaultHttpClient available till Apache HTTP Library version 4.2 and org.apache.http.impl.client.CloseableHttpClient available since Apache HTTP Library version 4.3. DefaultHttpClient is deprecated class now, so it’s suggested to use CloseableHttpClient class.

Bypass SSL Certificate Checking using CloseableHttpClient

If you are working with latest versions of apache http library, you should this version of code.

public static CloseableHttpClient getCloseableHttpClient()
{
	CloseableHttpClient httpClient = null;
	try {
		httpClient = HttpClients.custom().
				setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).
		        setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
		        {
		            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
		            {
		                return true;
		            }
		        }).build()).build();
	} catch (KeyManagementException e) {
		LOGGER.error("KeyManagementException in creating http client instance", e);
	} catch (NoSuchAlgorithmException e) {
		LOGGER.error("NoSuchAlgorithmException in creating http client instance", e);
	} catch (KeyStoreException e) {
		LOGGER.error("KeyStoreException in creating http client instance", e);
	}
	return httpClient;
}

To use CloseableHttpClient instance, use it in below manner.

//Some custom method to craete HTTP post object
HttpPost post = createPostRequest(); 

//Get http client
CloseableHttpClient httpClient = getCloseableHttpClient();

//Execute HTTP method
CloseableHttpResponse res = httpClient.execute(post);

//Verify response
if(res.getStatusLine().getStatusCode() == 200)
{
	String json = EntityUtils.toString(res.getEntity());
}

Bypass SSL Certificate Checking using DefaultHttpClient

If you are working on older versions of apache http library, you should this version of code.

public static DefaultHttpClient getDefaultHttpClient() throws Exception 
{
	DefaultHttpClient httpClient = new DefaultHttpClient();
	SSLContext ssl_ctx = SSLContext.getInstance("TLS");
	TrustManager[] certs = new TrustManager[] { new X509TrustManager() {
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public void checkClientTrusted(X509Certificate[] certs, String t) {
		}

		public void checkServerTrusted(X509Certificate[] certs, String t) {
		}
	} };
	ssl_ctx.init(null, certs, new SecureRandom());
	SSLSocketFactory ssf = new SSLSocketFactory(ssl_ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
	ClientConnectionManager ccm = httpClient.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", 443, ssf));
	return new DefaultHttpClient(ccm, httpClient.getParams());
}

To use DefaultHttpClient instance, use it in below manner.

//Some custom method to craete HTTP post object
HttpPost post = createPostRequest(); 

//Get http client
DefaultHttpClient client = getDefaultHttpClient();

//Execute HTTP method
HttpResponse httpResponse = client.execute(post);

//Handle response
Once again, please do not use it on production environment because it defeats the whole purpose of having SSL security on first place.

Possible Exception Message of SSLHandshakeException

In case you have not setup the above code correctly, you may find below exception message. This message confirms that SSL certificate matching is still failing.

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
	at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1916)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:279)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:273)
	at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1472)
	at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:213)
	at sun.security.ssl.Handshaker.processLoop(Handshaker.java:913)
	at sun.security.ssl.Handshaker.process_record(Handshaker.java:849)
	at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1035)
	at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1344)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1371)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
	at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:394)
	at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:353)
	at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:141)
	at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
	at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
	at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
	at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
	at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
	at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
	at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)

Drop me your questions in comments section.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Abiya

    January 25, 2017

    It is by the the best reference on how to enter the field, especially putting things into context, which in your case is framing it outside of learning programming languages, and more towards what concepts you should learn.

  2. Bhagwati Prasad

    December 29, 2016

    Hello sir!

    If you could please tell me, what technologies have you used to make this website? On Front end and on the back end as well?

    Thank you in advance! 🙂

  3. mythily mythu

    November 2, 2016

    Excellent post!!! The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.

  4. Harini

    October 12, 2016

    i am new to concepts of whatever you explain above. can you explain me with scree shot of work how to do it?
    i am not that much knowledge about SSL Certificate can you give some more details about SSL certification and how can it perform?
    Regards,
    Harini.

Comments are closed on this article!

Search Tutorials

Java Security Tutorial

  • Java – Generate Secure Hash
  • Java – Debug SSL Issues
  • Java – AES Algorithm
  • Java – AES 256
  • Java – REST Security Guide
  • Java – Bypass SSL Checking
  • Java – Set Env Variables without Admin Access

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces