Nakov.com

Thoughts on Software Engineering

  • About
  • Books
  • Courses
  • Videos
  • Presentations
  • Research
  • Publications
  • Others
  • Contacts
  • RSS Feed
  • Home

Categories

  • .net (81)
  • blog (330)
  • bulgarian (203)
  • career (21)
  • contests (28)
  • courses (64)
  • english (131)
  • HTML5 (6)
  • java (44)
  • seminars (81)
  • НЛП (7)
  • предприемачество (3)

Networked Blogs

Follow this blog

Recent Posts

  • Представяне на NASA Space Apps Challenge на 2 април 2013
  • Как да презентираме вдъхновяващо с майсторлък? Мурафетите на Наков
  • Пролетен прием в софтуерната академия: 500 нови студента от април
  • Безплатен курс “Бизнес умения за софтуерни инженери” – от 27 март
  • 580 продължават безплатното си обучение в софтуерната академия след изпитите по CSS и C# част 2

Partners

Intro C# Programming Book by Svetlin Nakov
Telerik Academy

My Projects

  • GWT Advanced Table
  • Internet Programming with Java Book
  • Intro C# Programming Book
  • Intro Java Programming Book
  • Java For Digitally Signing Documents In Web Book
  • Programming for .NET Framework Book
  • Software University

Useful Links

  • Bulgarian Association of Software Developers (BASD)
  • Free Java and Java EE Course
  • NLP Club Bulgaria
  • Stefan Kanev's Blog
  • Telerik Academy
  • Telerik Kids Academy
  • Telerik School Academy

Tags

AJAX ASP.NET C# CSS development HTML Java JavaScript NET Programming Software SQL telerik Академия на Телерик Академия на Телерик за ученици академия академия за софтуерни инженери безплатен курс безплатни курсове безплатни уроци безплатно безплатно обучение курс обучение програмиране разработка на софтуер семинар софтуерна академия състезание телерик

Most Viewed Posts

  • Rejected a Program Manager Position at Microsoft Dublin – My Successful Interview at Microsoft
  • Svetlin Nakov – About Me
  • Innovations in Software Тest Automation – конференция за QA инженери – 25.11.2011
  • Online AES Encryption Tool
  • Disable Certificate Validation in Java SSL Connections
  • My Interview at Google in Zurich
  • Native SQL Queries in Entity Framework
  • JAX-RS, @Path, @PathParam and Optional Parameters
  • Svetlin Nakov – Books
  • NHibernate Lazy Loading BLOB column

Author: Svetlin Nakov

July 16, 2009

  • Svejo.net
  • Tweet

Disable Certificate Validation in Java SSL Connections

By design when we open an SSL connection in Java (e.g. through java.net.URL.openConnection(“https://….”)) the JSSE implementation of the SSL protocol performs few validations to ensure the requested host is not fake. This involves validation of the server’s X.509 certificate with the PKIX algorithm and checking the host name agains the certificate subject. If the SSL certificate is not validates as trusted or does not match the target host, an HTTPS and other SSL encrypted connection cannot be established and all attempts will result in SSLHandshakeException or IOException.

Example of HTTPS Connection in Java that will Fail Due to Certificate Validation Failure

Consider we are trying to download a resource from HTTPS server:

URL url = new URL("https://www.nakov.com:2083/");
URLConnection con = url.openConnection();
Reader reader = new InputStreamReader(con.getInputStream());
while (true) {
	int ch = reader.read();
	if (ch==-1) {
		break;
	}
	System.out.print((char)ch);
}

If the server uses self-signed X.509 certificate, we will get SSLHandshakeException the following exception during the SSL handshaking:

Exception in thread "main" 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 com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
	at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
	...

This exception can be avoided if we import the server’s self-signed certificate in the JVM trusted store, a file called “cacerts”. For more information see this post: http://www.java-samples.com/showtutorial.php?tutorialid=210.

We could have also another issue. If the server uses trusted certificate (issued from trusted CA like VeriSign), but for different host, we will get another exception (IOException) during the host verification step of the SSL handshaking:

Exception in thread "main" <strong>java.io.IOException: HTTPS hostname wrong: should be <www.nakov.com></strong>
	at sun.net.www.protocol.https.HttpsClient.checkURLSpoofing(Unknown Source)
	at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
	at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)

How to Turn Off Certificate Validation in Java HTTPS Connections?

Avoiding these exceptions is possible by switching off the certificate validation and host verification for SSL for the current Java virtual machine. This can be done by replacing the default SSL trust manager and the default SSL hostname verifier:

import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;

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;
import java.security.cert.X509Certificate;

public class Example {
	public static void main(String[] args) throws Exception {
		// Create a trust manager that does not validate certificate chains
		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 = 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;
			}
		};

		// Install the all-trusting host verifier
		HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

		URL url = new URL("https://www.nakov.com:2083/");
		URLConnection con = url.openConnection();
		Reader reader = new InputStreamReader(con.getInputStream());
		while (true) {
			int ch = reader.read();
			if (ch==-1) {
				break;
			}
			System.out.print((char)ch);
		}
	}
}

Voilla! Now the code runs as expected: it downloads the resource from an https address with invalid certificate.

Be careful when using this hack! Skipping certificate validation is dangerous and should be done in testing environments only.

Tags: cacerts, certificate, certificate validation, host verification, HostnameVerifier, HTTPS, HTTPS hostname wrong, IOException, Java, java samples, java ssl, java url, java.net.URL, JSSE, PKIX, PKIX path building failed, security, self-signed X.509 certificate, SSL, SSL hostname verifier, SSL trust manager, SSLHandshakeException, TrustManager, URLConnection, X.509 certificate

Previews (28,877), Views (26,010), Comments (27)

27 Comments »

  1. Can this code be used in j2me?

    Thanks

    Comment by Amer — January 29, 2011 @ 02:27

  2. I don’t know. You could test it in Java ME environment, of course.

    Comment by nakov — January 30, 2011 @ 18:53

  3. Is this supposed to work when running the client from the command line? I have implemented this but I am still receiving the same error. You have any idea what may be happening?

    Comment by kaz — September 15, 2011 @ 06:45

  4. I have no idea. It worked at the time it was written. Now we have newer Java versions that could possibly work differently.

    Comment by nakov — September 15, 2011 @ 14:17

  5. It works … I found the issue I was having … it was in an old script that was being used to run the client. ;-) it was setting the command line parameter: -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol … which apparently did not recognize my hostname verifier. Thx for the response.

    JFYI … all that is needed when using JAX-WS is:

    HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier() {
    public boolean verify(String urlHostName, SSLSession session) {
    log.debug( “Warning: URL Host: ” + urlHostName + ” vs. ” + session.getPeerHost() );
    return true;
    }
    } );

    Comment by kaz — September 15, 2011 @ 21:05

  6. [...] to a HTTPS server from Java and ignore the validity of the security certificate as well as Disable Certificate Validation in Java SSL Connections, but the accepted answer to the first is for HttpClient 4.0 (unfortunately I cannot upgrade, unless [...]

    Pingback by How to make Apache Commons HttpClient 3.1 ignore HTTPS certificate invalidity? | Gravity Layouts — October 7, 2011 @ 11:50

  7. This is very helpful, it worked perfectly. The one change I did was making these two calls on the connection instance (instead of static calls)

    httpsConnection.setSSLSocketFactory(sc.getSocketFactory());
    httpsConnection.setHostnameVerifier(allHostsValid);

    Comment by Madhu — October 27, 2011 @ 19:32

  8. [...] I actually disabled the HTTPS certificate check by using the method described in this nifty blog: http://www.nakov.com/blog/2009/07/16/disable-certificate-validation-in-java-ssl-connections/. In actual production use, however, HTTPS URLs are handled by using the actual certificates [...]

    Pingback by How to read the file size of a document served at an HTTP/S URL using Java « Talking with a Lisp — December 4, 2011 @ 20:04

  9. Sweet – just what I needed – thank you. Only thing I needed to add was a permission in my java.policy file like so:
    permission javax.net.ssl.SSLPermission “setHostnameVerifier”;

    Comment by Mikkel Flindt Heisterberg — January 10, 2012 @ 19:08

  10. [...] przejść do strony z wątpliwym (niezaufanym) certyfikatem SSL – http://www.nakov.com/blog/2009/07/16/disable-certificate-validation-in-java-ssl-connections/ – w [...]

    Pingback by Ciekawostki różne « Wiadomości o technologiach IT — January 27, 2012 @ 17:42

  11. Thank you very much!!!! very usefull!

    Comment by Federico — March 26, 2012 @ 16:43

  12. it works, thanks much

    Comment by Prafulla — March 30, 2012 @ 08:15

  13. it works, great help!!

    Comment by Prafulla — March 30, 2012 @ 08:16

  14. Very great, thank you!

    Comment by Daniel — April 17, 2012 @ 16:26

  15. Thanks. Very helpful — I was using a similar but incomplete solution that worked in some cases but not all. Not sure why it sometimes worked but anyhow, this is great!

    Comment by jeff — July 8, 2012 @ 03:28

  16. Hello! fddgegf interesting fddgegf site! I’m really like it! Very, very fddgegf good!

    Comment by Pharmd57 — September 9, 2012 @ 03:46

  17. Thanks…
    Very Helpful

    Comment by Shashank — October 3, 2012 @ 13:35

  18. Can anybody help me why am I getting the following error ?
    Exception in thread “main” java.io.IOException: Server returned HTTP response code: 401 for URL: https://www.nakov.com:2083/
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1615)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at MainProject.Cert.main(Cert.java:58)

    Comment by me — October 28, 2012 @ 04:56

  19. This URL requires authentication (username + password). It says “401 Access Denied” and this is its correct behavior. HTTP code 401 is returned when the server needs authentication. You could try accessing another URL, e.g. https://appharbor.com/.

    Comment by nakov — October 28, 2012 @ 18:44

  20. @nakov: the example you provided: https://appharbor.com/. has a valid certificate. So, Java can deal with it without the need to use the code. Can you provide me with another example for expired or self-signed certificate if you have any ?

    Comment by me — October 30, 2012 @ 23:49

  21. You are right. Here are few other examples of HTTPS-based URLs with self-signed (invalid) certificates:
    https://fmi.uni-sofia.bg
    https://vasil.ludost.net
    https://openfmi.net

    Comment by nakov — October 31, 2012 @ 13:45

  22. [...] http://www.nakov.com/blog/2009/07/16/disable-certificate-validation-in-java-ssl-connections/  Comment  十31 [...]

    Pingback by Elbelife | 易北生活 — November 9, 2012 @ 19:24

  23. [...] http://www.nakov.com/blog/2009/07/16/disable-certificate-validation-in-java-ssl-connections/ Like this:LikeBe the first to like this. [...]

    Pingback by View a PDF Securely « Asa Welle's Oracle ADF Blog — November 14, 2012 @ 06:11

  24. Excellent post. Vey nice!!

    Comment by Raj — November 15, 2012 @ 14:56

  25. I was very happy to seek out this internet-site.I needed to thanks for your time for this glorious learn!! I positively enjoying each little little bit of it and I have you bookmarked to take a look at new stuff you weblog post. ralph lauren polo http://cheap-ralph-lauren-polos.webs.com/

    Comment by ralph lauren polo — March 13, 2013 @ 11:49

  26. Just a note if you use HTTPS Mutual SSL Authentication, this can cause a “sslv3 alert bad certificate” error.
    javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    as it nulls the SSL certs needed for the two-way handshake.
    Its fine to use this code if you do not use Mutual SSL Auth.

    Comment by Russell Grokett — April 8, 2013 @ 22:05

  27. how do I pass username and password to the htpps connection.
    I am trying this but its not working

    byte[] encodedPassword = ( userName + “:” + password ).getBytes();
    BASE64Encoder encoder = new BASE64Encoder();
    con.setRequestProperty( “Authorization”,
    “Basic ” + encoder.encode( encodedPassword ) );

    Comment by Abhishek — April 19, 2013 @ 06:52

RSS feed for comments on this post. TrackBack URL

Leave a comment

Top Posts

  • Семинар “Как да си намерим работа в ИТ индустрията?” – CV, cover letter, интервю

  • Университет като за софтуерни инженери: къде да учим програмиране след 12 клас? (класацията на Наков)

  • Rejected a Program Manager Position at Microsoft Dublin – My Successful Interview at Microsoft

  • My Interview at Google in Zurich

Translation

Recent Posts

  • Представяне на NASA Space Apps Challenge на 2 април 2013
  • Как да презентираме вдъхновяващо с майсторлък? Мурафетите на Наков
  • Пролетен прием в софтуерната академия: 500 нови студента от април
  • Безплатен курс “Бизнес умения за софтуерни инженери” – от 27 март
  • 580 продължават безплатното си обучение в софтуерната академия след изпитите по CSS и C# част 2

Recent Comments

  • extra resources on Семинар “Как да си намерим работа в ИТ индустрията?” – CV, cover letter, интервю: While farmacia on line has won wide acceptance, it has served Southeast Asian doctors for...
  • http://theprostitutiontimes.blogspot.com on Нов безплатен курс по уеб дизайн с HTML 5, CSS и JavaScript – от март в академията на Телерик: Instead, it's diverted hundreds of millions of dollars to two children with autism for" pain...
  • Paul Crocker on X.509 Certificate Validation in Java: Build and Verify Chain and Verify CLR with Bouncy Castle: Thanks - It works fine for me after tidying the code up a bit and...
  • look at this web-site on Безплатните курсове в Академията на Телерик за софтуерни инженери – какво да очакваме за 2011-2012?: But beyond the financial implications it is the most logical thing in the world, but...
  • check This link right Here now on 85 продължават в Софтуерната академия в курса Software Engineering Basics от 17 април: Isn't the very name," National News" mean that it s not just about themedication. Our...

Archives

  • March 2013 (4)
  • February 2013 (5)
  • January 2013 (7)
  • December 2012 (1)
  • November 2012 (11)
  • October 2012 (8)
  • September 2012 (8)
  • August 2012 (2)
  • July 2012 (10)
  • June 2012 (1)
  • May 2012 (9)
  • April 2012 (9)
  • March 2012 (9)
  • February 2012 (10)
  • January 2012 (8)
  • December 2011 (5)
  • November 2011 (12)
  • October 2011 (18)
  • September 2011 (16)
  • August 2011 (7)
  • July 2011 (7)
  • June 2011 (2)
  • May 2011 (3)
  • April 2011 (10)
  • March 2011 (8)
  • February 2011 (5)
  • January 2011 (7)
  • December 2010 (3)
  • November 2010 (17)
  • October 2010 (8)
  • September 2010 (4)
  • August 2010 (2)
  • July 2010 (4)
  • June 2010 (3)
  • May 2010 (4)
  • April 2010 (2)
  • March 2010 (1)
  • February 2010 (2)
  • January 2010 (4)
  • December 2009 (3)
  • November 2009 (6)
  • October 2009 (3)
  • September 2009 (6)
  • July 2009 (4)
  • June 2009 (1)
  • May 2009 (3)
  • December 2008 (2)
  • November 2008 (2)
  • September 2008 (1)
  • August 2008 (5)
  • July 2008 (2)
  • June 2008 (4)
  • May 2008 (2)
  • April 2008 (1)
  • March 2008 (2)
  • February 2008 (2)
  • January 2008 (1)
  • December 2007 (4)
  • November 2007 (7)
  • October 2007 (3)
  • September 2007 (9)
  • August 2007 (5)

RSS Academy Forums

  • Answered: [КПК Изпит] Вариант 2 - Phonebook
  • Answered: Проблем при сваляне на домашно за оценяване
  • Answered: Неофициални резултати по JS 2
  • Answered: "C# - част I" дати на теста и изпита???
  • Answered: [C#] Домашно Operators and Expressions - 7 Задача

navigation:

Home About Books Courses Presentations Videos Research Publications Others Contacts
Svetlin Nakov @ Google+

My Projects

  • GWT Advanced Table
  • Internet Programming with Java Book
  • Intro C# Programming Book
  • Intro Java Programming Book
  • Java For Digitally Signing Documents In Web Book
  • Programming for .NET Framework Book
  • Software University

Useful Links

  • Bulgarian Association of Software Developers (BASD)
  • Free Java and Java EE Course
  • NLP Club Bulgaria
  • Stefan Kanev's Blog
  • Telerik Academy
  • Telerik Kids Academy
  • Telerik School Academy

Categories

  • .net
  • blog
  • bulgarian
  • career
  • contests
  • courses
  • english
  • HTML5
  • java
  • seminars
  • НЛП
  • предприемачество

Recent Posts

  • Представяне на NASA Space Apps Challenge на 2 април 2013
  • Как да презентираме вдъхновяващо с майсторлък? Мурафетите на Наков
  • Пролетен прием в софтуерната академия: 500 нови студента от април
  • Безплатен курс “Бизнес умения за софтуерни инженери” – от 27 март
  • 580 продължават безплатното си обучение в софтуерната академия след изпитите по CSS и C# част 2

Copyright © 1999 - 2013 Svetlin Nakov