<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>certificate &#8211; Pauls Blog</title>
	<atom:link href="https://sterl.org/tag/certificate/feed/" rel="self" type="application/rss+xml" />
	<link>https://sterl.org</link>
	<description></description>
	<lastBuildDate>Fri, 20 Sep 2019 13:24:58 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
	<item>
		<title>Java SSLContext and the SSLSocketFactory self-signed certificate</title>
		<link>https://sterl.org/2016/07/self-signed-certificate-java-sslcontext-and-sslsocketfactory/</link>
					<comments>https://sterl.org/2016/07/self-signed-certificate-java-sslcontext-and-sslsocketfactory/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Tue, 19 Jul 2016 15:10:53 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[certificate]]></category>
		<category><![CDATA[SSL]]></category>
		<guid isPermaLink="false">http://sterl.org/?p=175</guid>

					<description><![CDATA[Problem 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: Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Problem</h2>



<p>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: </p>



<pre>
Caused by: 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.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
	at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
	at sun.security.validator.Validator.validate(Validator.java:260)
	at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
	at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
	at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
	at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1479)
	... 47 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145)
	at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)
	at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
	at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
	... 53 more
</pre>



<h2 class="wp-block-heading">Solution</h2>



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



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



<ul class="wp-block-list"><li> SSLSocketFactory &#8212; creates the Socket connection in case of an SSL connection </li><li> SSLContext &#8212; responsible for the verification of the certificate </li></ul>



<h3 class="wp-block-heading">Export Certificate</h3>



<p> First, we need to get the certificate. Either use Firefox to download it or the command line: </p>



<pre class="wp-block-code"><code>openssl s_client -connect google.de:443 -showcerts</code></pre>



<p>The <code>pem</code> file is here e.g.: </p>



<pre>
-----BEGIN CERTIFICATE-----
MIIDfTCCAuagAwIBAgIDErvmMA0GCSqGSIb3DQEBBQUAME4xCzAJBgNVBAYTAlVT
MRAwDgYDVQQKEwdFcXVpZ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wUCEm2u+WR74M26x1W
b8ravHNjkOR/ez4iyz0H7V84dJzjA1BOoa+Y7mHyhD8S
-----END CERTIFICATE-----
</pre>



<h3 class="wp-block-heading">Create SSLContext including the Certificate</h3>



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



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public static SSLContext buildSslContext(InputStream... inputStreams) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
  X509Certificate cert;
  KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  trustStore.load(null);

  for (InputStream inputStream : inputStreams) {
    try {
      CertificateFactory certificateFactory = CertificateFactory.getInstance(&quot;X.509&quot;);
      cert = (X509Certificate)certificateFactory.generateCertificate(inputStream);
    } finally {
      IOUtils.closeQuietly(inputStream);
    }
    String alias = cert.getSubjectX500Principal().getName();
    trustStore.setCertificateEntry(alias, cert);
  }

  TrustManagerFactory tmf = TrustManagerFactory.getInstance(&quot;X509&quot;);
  tmf.init(trustStore);
  TrustManager[] trustManagers = tmf.getTrustManagers();
  SSLContext sslContext = SSLContext.getInstance(&quot;TLS&quot;);
  sslContext.init(null, trustManagers, null);

  return sslContext;
}</pre></div>



<h3 class="wp-block-heading">Put the SSLSocketFactory together </h3>



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



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">SSLContext sslContext = CryptoUtil.buildSslContext(
  this.getClass().getResourceAsStream(&quot;/my-cert.pem&quot;));
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);</pre></div>



<p>Now we have the SSLSocketFactory, lets put it to use. </p>



<h3 class="wp-block-heading">Use the SSLConnectionSocketFactory</h3>



<p>Here I will use the created socket factory to configure the Apache HTTP client and use it again in the Spring RestTemplate: </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">// this two lines are just repeated from above
SSLContext sslContext = CryptoUtil.buildSslContext(this.getClass().getResourceAsStream(&quot;/beta-comfylight-cert.pem&quot;));
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

// here we create the Http Client using our SSL Socket Factory and so trust relation
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);

// create the spring REST Template using our apache HTTP client
RestTemplate restTemplate = new RestTemplate(requestFactory);</pre></div>



<h2 class="wp-block-heading">Summary</h2>



<p>What have we achieved now?</p>



<ul class="wp-block-list"><li>We have an SSL Socket Factory which just trust our &#8222;server&#8220; / &#8222;certificate&#8220;</li><li>We haven&#8217;t overwritten any default socket factory in the application, which could cause problems in other subsystems as we then just trust &#8222;us&#8220;</li><li>We haven&#8217;t used a trust all, which would be fine for a test but would render the SSL encryption useless in production (<a href="https://en.wikipedia.org/wiki/Man-in-the-middle_attack">man in the middle attack</a>&#8230;)</li></ul>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2016/07/self-signed-certificate-java-sslcontext-and-sslsocketfactory/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
