Java SSLContext and the SSLSocketFactory self signed certificate


Often we want to connect to create a secure SSL connection to an HTTPs endpoint which is secured by a self signed Certificate. If we do so just with a simple call we usually face an nice exception like :


Often I see that either somebody uses an trust all or just overwrites the default Socket Factory (HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())).  This is maybe okay for just a test but should be used in production ready code.

Overall it is simple to fix it. We just need to know how the stuff works. In short we have usually always:

  • SSLSocketFactory — creates the Socket connection in case of an SSL connection

  • SSLContext — responsible for the verification of the certificate

Export Certificate

First we need to get the certificate. Either use Firefox to download it or the command line:

The pem file is here e.g.:

Create SSLContext including the Certificate

You can either import this pem file into your trust store or just create the trust store using the pem on the fly:

Put the SSLSocketFactory together

I assume the pem file is in the source folder here, for maven src/main/resources.

Now we have the SSLSocketFactory, lets put it to use.

Use the SSLConnectionSocketFactory

Here I will use the the created socket factory to configure the apache HTTP client and use it again in the Spring RestTemplate:


What have we achieved now?

  • We have an SSL Socket Factory which just trust our „server“ / „certificate“
  • We haven’t overwritten any default socket factory in the application, which could cause problems in other subsystems as we then just trust „us“
  • We haven’t used a trust all, which would be fine for a test but would render the SSL encryption useless in production (man in he middle attack…)

Paul Sterl has written 20 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">