Disabling Certificate Validation in an HTTPS Connection

By default, accessing an HTTPS URL using the URL class results in an exception if the server's certificate chain cannot be validated has not previously been installed in the truststore. If you want to disable the validation of certificates for testing purposes, you need to override the default trust manager with one that trusts all certificates.
// 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(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

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

// Now you can access an https URL without having the certificate in the truststore
try {
    URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}

Comments

21 Jan 2010 - 12:35pm by Anonymous (not verified)

good page

10 Feb 2010 - 6:37am by Anonymous (not verified)

Not verifying the server's certificate makes such an SSL connection vulnerable to MITM attacks (just like anonymous cipher suites), so SSL isn't really useful in this case...

10 Feb 2010 - 11:09pm by Anonymous (not verified)

I think the point is testing, against servers that have either self-signed certificates or are borrowing ones from other servers (for testing). Yes you lose some security, but your testing works.

5 Mar 2010 - 7:21am by jarsit (not verified)

Yes cool, too bad that is not working for me, until one day ago the certificates was ok now I'm stuck with this certificate error.

5 Mar 2010 - 8:13am by jarsit (not verified)

Ok this page code is ok if i replace

SSLContext sc = SSLContext.getInstance("SSL");

with

SSLContext sc = SSLContext.getInstance("TLS");

and is working.

21 May 2010 - 4:05am by Anubrato (not verified)

Very helpful! Thanks so much!

12 Jul 2010 - 8:53am by Amon RA (not verified)

Thank you very much. You solved my biggest problem in the project.

22 Jul 2010 - 6:59am by SJ Baker (not verified)

adding

HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
public boolean verify(String string,SSLSession ssls) {
return true;
}
});

should avoid the HTTPS hostname wrong: exception.

30 Sep 2010 - 1:23pm by Jonathan Matthews (not verified)

Fantastic example, thanks to the author. The next version of our site checker (DeepTrawl) will now work much better with certs.

21 Oct 2010 - 3:10pm by Rahul (not verified)

Thanks author. and thanks to Jarsit.
It worked with below change.
"
Ok this page code is ok if i replace

SSLContext sc = SSLContext.getInstance("SSL");

with

SSLContext sc = SSLContext.getInstance("TLS");

and is working."

5 Nov 2010 - 6:55pm by radley bags (not verified)

In my case I always need to secure my domains for the main reason that I hate spammers. But still I find this very useful anytime I will have to disable my https connection. radley bags

12 Nov 2010 - 12:12pm by Subhas Bose (not verified)

Gr8 Help.. I just did copy, paste work .. The code works fine to connect to https urls..

15 Nov 2010 - 6:57am by Anonymous (not verified)

any similar solution for .Net?

1 Dec 2010 - 1:47am by Ciara at cheap ski boots (not verified)

Can I just set https directly in Wordpress? If yes, then another concern.Can I then override the default trust manager with one that trusts all certificates?

23 Dec 2010 - 7:45pm by Swapna (not verified)

Hey
I have tried the above example. But it doesn't work for me. It still throws the javax.net.ssl.SSLException Not trusted server certificate. I am trying it on Android. My code looks like:

public void run() {
try {

TrustManager[] trustAllCerts = new TrustManager[]{new 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) {
}
}
};

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

try {
// Create the client socket
int port = 443;
String hostname = "myhostname"; //I have put my hostname here.
SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
SSLSocket socket = (SSLSocket)factory.createSocket(hostname, port);

// Connect to the server
socket.startHandshake();

// Retrieve the server's certificate chain
java.security.cert.Certificate[] serverCerts = socket.getSession().getPeerCertificates();

// Close the socket
socket.close();
} catch (SSLPeerUnverifiedException e) {
} catch (IOException e) {
}
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 20000); // 20 secs
HttpPost httpPost = new HttpPost(serverpath);
httpPost.setEntity(new StringEntity(request.getRequestData()));
HttpResponse response = httpClient.execute(httpPost);

// process response
wrapper.setResponse(response);
handler.post(wrapper);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

24 Dec 2010 - 1:36am by giriBabu (not verified)

Hi, please tell me where i have to place this code to test
thanks in advance
Giri

25 Jan 2011 - 4:43am by Darshan S (not verified)

Hi ..
Thanks for post!!! Its a great help.
Can anyone help me in the following scenerio:
I am trying to get an instance of a remote weblogic server through an java client which is an SSL enabled with an self signed certificate.How can i use the above code to avoid the SSL handshake expection.
Please any help will be of a great help!!!

The below is the piece of code i am using to get an initial context to the weblogic server.
public InitialContext getContext(String integrationId) {
InitialContext ctx = null;
try {
Properties env = new Properties();
env.put(Context.PROVIDER_URL, "t3://10.10.201.41:8011");
env.put(Context.SECURITY_PRINCIPAL, "weblogic");
env.put(Context.SECURITY_CREDENTIALS, "welcome1");
env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
ctx = new InitialContext(env);

}catch(Exception e) {
System.out.println(integrationId+" ==> "+e.getMessage());
e.printStackTrace();
}
return ctx;
}

27 Jan 2011 - 9:50am by Anonymous (not verified)

When I run this code, it shows me exception:

java.lang.NoClassDefFoundError: javax/net/ssl/TrustManager

Where should I put this code?

Thank you

27 Jan 2011 - 11:08pm by lobotomi (not verified)

thank you thank you thank you!!!! u save my life... lol

28 Jan 2011 - 5:44pm by Anonymous (not verified)

Can this work in j2me?

8 Feb 2011 - 4:59am by Anonymous (not verified)

¡Muchas gracias! Funciona.
Many thanks! It works.

19 Feb 2011 - 9:13pm by Anonymous (not verified)

But There's no TrustManager class for j2me. So How I could disable certificate validation for j2me mobile client

15 Mar 2011 - 3:20pm by Anonymous (not verified)

thanks..u saves lot of my time..

21 Mar 2011 - 12:07pm by Eli (not verified)

Very Good, but there is a way to trust only in your own certificate like *.yourdomain.com?

22 Mar 2011 - 1:05am by Anonymous (not verified)

please, how can i make this work for POP3SSLStore ?

14 Apr 2011 - 1:34pm by Englebart (not verified)

In reply to 21 mar 2011
See posting on 22 Jul 2010 - 6:59am by SJ Baker (not verified)
but instead of just returning true compare (case insensitive) the string versus the certificate name that you pull from the SSLSession's certificate. Just set a debugger breakpoint and figure out where the certificate has the server name.

4 May 2011 - 11:09pm by Sagar (not verified)

Excellent ..it worked fine ..just copy paste..Any disadvantages.?

15 May 2011 - 4:31am by Jon (not verified)

It works. You are a genius.

19 May 2011 - 11:34am by Anil (not verified)

You made my day.

I also had to do add the setDefaultHostnameVerifier call . Otherwise I was getting the hostname error.

19 Jul 2011 - 7:43am by Shilpa (not verified)

It worked for me. Save me lot of trouble. Thanks a lot. I also need to add setDefaultHostnameVerifier call.

8 Aug 2011 - 5:18am by Anonymous (not verified)

Real Classy.... Thank you very much.... Very good page.

8 Sep 2011 - 1:04am by kalohr (not verified)

make sure to set the host name verifier

httpsURLConnection.setDefaultHostnameVerifier(hv);

21 Sep 2011 - 10:18am by Dave (not verified)

First I would like to say thanks for posting the original solution. Secondly I am not that well versed in certificate handling so please bear with me.

I implemented the code for trusting all certificates into a JUnit test case that exercises a class that makes an HTTPS request to an external site. However I was concerned about the MITM vulnerability, so I attempted to eliminate the MITM vulnerability with the code shown below.

I exported from my web browser to the xxxx.crt file the public (???) certificate that was downloaded to the browser when I accessed the site via the browser.

When running through debug I can see that the certs array is invoked with 4 certificates, the first certificate in the array is the certificate from the external site in question. I assumed by comparing (verify method) the certificates in the array with the certificate in the file that a match would be found on at least one of the certificates in the array, thereby eliminating the MITM vulnerability.

However as the code loops through the array the SignatureException is thrown on every iteration.

Does anyone have any insight as to why this does not work as expected.

And if I can get this to work without throwing an exception then is it truly eliminating the MITM vulnerability?


public void checkServerTrusted(X509Certificate[] certs, String authType) {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("xxxx.crt");

try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate publicCert = cf.generateCertificate(is);
PublicKey publicKey = publicCert.getPublicKey();
boolean validSignature = false;

for (int i = 0; i < certs.length; i++) {
try {
certs[i].verify(publicKey);
validSignature = true;
break;

} catch (SignatureException e) {
}
}

if (!validSignature) {
throw new SignatureException();
}

} catch (InvalidKeyException e) {
throw new RuntimeException(e);

} catch (java.security.cert.CertificateException e) {
throw new RuntimeException(e);

} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);

} catch (NoSuchProviderException e) {
throw new RuntimeException(e);

} catch (SignatureException e) {
throw new RuntimeException(e);
}
}

3 Oct 2011 - 9:30am by business loans (not verified)

People deserve good life and personal loans or secured loan can make it better. Just because people's freedom depends on money state.

16 Oct 2011 - 11:19am by Ahmedshaqoshaqo (not verified)

Conect me

31 Oct 2011 - 8:47am by William Valentim (not verified)

Excellent article.

14 Dec 2011 - 2:42am by JVMHost.com (not verified)

Thank you for the useful article. I found it looking for a solution for our java hosting client.

17 Dec 2011 - 6:17am by JeniferCHRISTIAN19 (not verified)

I propose not to hold off until you get big sum of money to order different goods! You can get the loans or just collateral loan and feel free

25 Dec 2011 - 5:14pm by Makailee (not verified)

That's the best aneswr of all time! JMHO

3 Jan 2012 - 9:38am by dhergert (not verified)

It would be nice if you could do this from the command line, unfortunately Java would have to ship either with an all trusting manager or allow for a flag to disable SSL verification, which I think it has neither. For example, startup java with
java -Dtrust.manager.class=java.ssl.managers.TrustAll DoWork

or a socketfactory that trusts all SSL connections. Ah well.

17 Feb 2012 - 4:07am by credit loans (not verified)

According to my own analysis, thousands of persons all over the world get the loan at good banks. So, there is good chances to receive a secured loan in every country.

23 Feb 2012 - 12:08am by dutt (not verified)

I tried to read https url via java it throws below exception
java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at sun.net.www.protocol.http.NTLMAuthentication.buildType3Msg(NTLMAuthentication.java:368)
at sun.net.www.protocol.http.NTLMAuthentication.setHeaders(NTLMAuthentication.java:225)
at sun.net.www.protocol.http.HttpURLConnection.doTunneling(HttpURLConnection.java:1557)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:183)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1139)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at java.net.URL.openStream(URL.java:1029)
at GoogleEx.main(GoogleEx.java:138)

24 Mar 2012 - 1:00pm by Anonymous (not verified)

it's excellent, thank you very much, me has salvao la vida tio!!!!

16 Apr 2012 - 1:08pm by Betek (not verified)

Hi there, I wonder if that change is performed permanently or only for the session? Thanks in advance.

20 Apr 2012 - 4:00pm by Anonymous (not verified)

Thanks to the original author and to SJ Baker all the way back in 2010 for the DefaultHostnameVerifier tip, which solved my problem!

2 May 2012 - 3:06am by Davis Shuma (not verified)

Thanks. This was very helpful and saved me alot of time.

17 Jun 2012 - 7:23pm by Wholesale New Era Hats (not verified)

The post is really the best on this laudable topic. I concur with your conclusions and will eagerly look forward to your future updates. Just saying thanks will not just be enough, for the exceptional lucidity in your writing. I will at once grab your rss feed to stay privy of any updates. De delightful work and much success in your business dealings!

6 Aug 2012 - 7:04am by personal loans (not verified)

Don't have a lot of money to buy some real estate? You not have to worry, just because it is available to take the mortgage loans to solve such kind of problems. Thus take a bank loan to buy everything you need.

10 Aug 2012 - 2:44am by Bob (not verified)

Does trusting all certificates cause performance issues? i.e. Do all requests require a new SSL handshake to be made beforehand?

15 Aug 2012 - 12:37am by fx pips (not verified)

Thanks for posting this informative post. I like the content because its very easy to understand. And the topic captures my attention. Keep on posting like this and more power!
check this site also fx pips

18 Aug 2012 - 4:27am by Govindarajan Narasimhan (not verified)

Best post I came across when searching for disabling certificates. Very easy to understand. Thanks.

21 Aug 2012 - 9:01am by Anonymous (not verified)

This worked great in Junit/Eclipse. However, it fails in WebLogic Server (10.3.5) for JAXB WS client which is accessed by Spring WebService Template. I have checked the JSSE checkbox in the WLS admin console but no luck.

3 Sep 2012 - 6:29am by mortgage loans (not verified)

Some time before, I really needed to buy a house for my business but I did not have enough cash and could not purchase something. Thank heaven my fellow proposed to take the loans goodfinance-blog.com at trustworthy bank. So, I acted so and was satisfied with my short term loan.

19 Sep 2012 - 9:25am by Elango muthu kumar (not verified)

I like it is pages

19 Sep 2012 - 9:27am by Elango muthu kumar (not verified)

I like it this pages

11 Oct 2012 - 5:55pm by Yumiko (not verified)

A marriage in any state is reicgnozed by any other state, unless you are gay, in which case some people think the full faith and credit and equal protection clauses can be waived (time will prove them wrong).

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.