How to Ignore Ssl Certificate Errors in Apache Httpclient 4.0

How to ignore SSL certificate errors in Apache HttpClient 4.0

You need to create a SSLContext with your own TrustManager and create HTTPS scheme using this context. Here is the code,

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

// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
System.out.println("getAcceptedIssuers =============");
return null;
}

public void checkClientTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkClientTrusted =============");
}

public void checkServerTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkServerTrusted =============");
}
} }, new SecureRandom());

SSLSocketFactory sf = new SSLSocketFactory(sslContext);
Scheme httpsScheme = new Scheme("https", 443, sf);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);

// apache HttpClient version >4.2 should use BasicClientConnectionManager
ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm);

Ignoring SSL certificate in Apache HttpClient 4.3

The code below works for trusting self-signed certificates. You have to use the TrustSelfSignedStrategy when creating your client:

SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
builder.build());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
sslsf).build();

HttpGet httpGet = new HttpGet("https://some-server");
CloseableHttpResponse response = httpclient.execute(httpGet);
try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
} finally {
response.close();
}

I did not include the SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER on purpose: The point was to allow testing with self signed certificates so you don't have to acquire a proper certificate from a certification authority. You can easily create a self-signed certificate with the correct host name, so do that instead of adding the SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER flag.

How to ignore SSL certificate errors in Apache HttpComponents HttpClient 5.1

There are several specialized builders in HC 5.1 that can be used to do the same:

CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(SSLConnectionSocketFactoryBuilder.create()
.setSslContext(SSLContextBuilder.create()
.loadTrustMaterial(TrustAllStrategy.INSTANCE)
.build())
.setHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build())
.build())
.build();

Ignore self-signed certificates in Apache HTTPClient 4.5

One of the above approaches should work in case of self-signed certificates, but the weird thing is you are getting same exception in all the approaches.

I feel during SSL session establishment or handshaking protocol is not being accepted either by client or by server.

The best solution here is to debug the application.

In case of tomcat, add -Djavax.net.debug=all in setenv.sh or setenv.bat files and then restart the server.

Or you can follow this tutorial.

The OP just needed to change the port when connecting to SSL:

//For HTTPS
HttpHost httpstarget = new HttpHost("mysite.com", 443, "https");

//For HTTP
HttpHost httptarget = new HttpHost("mysite.com", 80, "http");

How to ignore SSL certificate error using Apache HTTPClient but log it

It is just a simple matter of decorating X509TrustManager instances passed to the SSLContext#init method

static class TrustManagerDelegate implements X509TrustManager {

private final X509TrustManager trustManager;

TrustManagerDelegate(final X509TrustManager trustManager) {
super();
this.trustManager = trustManager;
}

@Override
public void checkClientTrusted(
final X509Certificate[] chain, final String authType) throws CertificateException {
trustManager.checkClientTrusted(chain, authType);
}

@Override
public void checkServerTrusted(
final X509Certificate[] chain, final String authType) {
try {
trustManager.checkServerTrusted(chain, authType);
} catch (CertificateException ex) {
// Implement proper logging;
System.out.println(chain[0]);
ex.printStackTrace(System.out);
}
}

@Override
public X509Certificate[] getAcceptedIssuers() {
return trustManager.getAcceptedIssuers();
}

}

...

TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init((KeyStore) null);
final TrustManager[] tms = tmfactory.getTrustManagers();
if (tms != null) {
for (int i = 0; i < tms.length; i++) {
final TrustManager tm = tms[i];
if (tm instanceof X509TrustManager) {
tms[i] = new TrustManagerDelegate((X509TrustManager) tm);
}
}
}
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tms, null);

CloseableHttpClient client = HttpClientBuilder.create()
.setSSLContext(sslContext)
.build();

How to handle invalid SSL certificates with Apache HttpClient?

https://mms.nw.ru uses a self-signed certificate that's not in the default trust manager set. To resolve the issue, do one of the following:

  • Configure SSLContext with a TrustManager that accepts any certificate (see below).
  • Configure SSLContext with an appropriate trust store that includes your certificate.
  • Add the certificate for that site to the default Java trust store.

Here's a program that creates a (mostly worthless) SSL Context that accepts any certificate:

import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class SSLTest {

public static void main(String [] args) throws Exception {
// configure the SSLContext with a TrustManager
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);

URL url = new URL("https://mms.nw.ru");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
System.out.println(conn.getResponseCode());
conn.disconnect();
}

private static class DefaultTrustManager implements X509TrustManager {

@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}

@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}

@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}

Apache Http Client SSL certificate error

Please also note that trusting self-signed certs does not mean trusting any arbitrary cert.

Try setting up your SSL context this way:

SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, 
new TrustStrategy() {
@Override
public boolean isTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
return true;
}
})
.useTLS()
.build();

Please also note that generally trusting certificates indiscriminately defeats the purpose of using SSL in the first place. Use when absolutely necessary or for testing only



Related Topics



Leave a reply



Submit