Question

How do you create SSL socket factory in new Apache Http Client 4.3 ?

Here is how I was creating it before 4.3

val ts = new TrustStrategy() {
  def isTrusted(chain: Array[X509Certificate], authType: String): Boolean = true
}

new SSLSocketFactory(ts, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)

Now SSLSocketFactory marked as deprecated. What is the new way of defining custom TrustStrategy ? I couldn't figure it out.

Was it helpful?

Solution

Well, I figured it out.

Initialize your ConnectionSocketFactory like this

val sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy).useTLS().build()
new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier())

If you take a look at sources of TrustSelfSignedStrategy the way they distinguish self-signed certificates from real ones is by checking length of chain.

public boolean isTrusted(
        final X509Certificate[] chain, final String authType) throws CertificateException {
    return chain.length == 1;
}

I'm not sure it's very reliable way but just keep it in mind. Maybe it's worth checking given X509Certificate in isTrusted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top