Trusting all certificates using HttpClient over HTTPS

725,425

Solution 1

Note: Do not implement this in production code you are ever going to use on a network you do not entirely trust. Especially anything going over the public internet.

Your question is just what I want to know. After I did some searches, the conclusion is as follows.

In HttpClient way, you should create a custom class from org.apache.http.conn.ssl.SSLSocketFactory, not the one org.apache.http.conn.ssl.SSLSocketFactory itself. Some clues can be found in this post Custom SSL handling stopped working on Android 2.2 FroYo.

An example is like ...

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.SSLSocketFactory;
public class MySSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

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

        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}

and use this class while creating instance of HttpClient.

public HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

BTW, the link below is for someone who is looking for HttpURLConnection solution. Https Connection Android

I have tested the above two kinds of solutions on froyo, and they all work like a charm in my cases. Finally, using HttpURLConnection may face the redirect problems, but this is beyond the topic.

Note: Before you decide to trust all certificates, you probably should know the site full well and won't be harmful of it to end-user.

Indeed, the risk you take should be considered carefully, including the effect of hacker's mock site mentioned in the following comments that I deeply appreciated. In some situation, although it might be hard to take care of all certificates, you'd better know the implicit drawbacks to trust all of them.

Solution 2

You basically have four potential solutions to fix a "Not Trusted" exception on Android using httpclient:

  1. Trust all certificates. Don't do this, unless you really know what you're doing.
  2. Create a custom SSLSocketFactory that trusts only your certificate. This works as long as you know exactly which servers you're going to connect to, but as soon as you need to connect to a new server with a different SSL certificate, you'll need to update your app.
  3. Create a keystore file that contains Android's "master list" of certificates, then add your own. If any of those certs expire down the road, you are responsible for updating them in your app. I can't think of a reason to do this.
  4. Create a custom SSLSocketFactory that uses the built-in certificate KeyStore, but falls back on an alternate KeyStore for anything that fails to verify with the default.

This answer uses solution #4, which seems to me to be the most robust.

The solution is to use an SSLSocketFactory that can accept multiple KeyStores, allowing you to supply your own KeyStore with your own certificates. This allows you to load additional top-level certificates such as Thawte that might be missing on some Android devices. It also allows you to load your own self-signed certificates as well. It will use the built-in default device certificates first, and fall back on your additional certificates only as necessary.

First, you'll want to determine which cert you are missing in your KeyStore. Run the following command:

openssl s_client -connect www.yourserver.com:443

And you'll see output like the following:

Certificate chain
 0 s:/O=www.yourserver.com/OU=Go to 
   https://www.thawte.com/repository/index.html/OU=Thawte SSL123 
   certificate/OU=Domain Validated/CN=www.yourserver.com
   i:/C=US/O=Thawte, Inc./OU=Domain Validated SSL/CN=Thawte DV SSL CA
 1 s:/C=US/O=Thawte, Inc./OU=Domain Validated SSL/CN=Thawte DV SSL CA
   i:/C=US/O=thawte, Inc./OU=Certification Services Division/OU=(c) 
   2006 thawte, Inc. - For authorized use only/CN=thawte Primary Root CA

As you can see, our root certificate is from Thawte. Go to your provider's website and find the corresponding certificate. For us, it was here, and you can see that the one we needed was the one Copyright 2006.

If you're using a self-signed certificate, you didn't need to do the previous step since you already have your signing certificate.

Then, create a keystore file containing the missing signing certificate. Crazybob has details how to do this on Android, but the idea is to do the following:

If you don't have it already, download the bouncy castle provider library from: http://www.bouncycastle.org/latest_releases.html. This will go on your classpath below.

Run a command to extract the certificate from the server and create a pem file. In this case, mycert.pem.

echo | openssl s_client -connect ${MY_SERVER}:443 2>&1 | \
 sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > mycert.pem

Then run the following commands to create the keystore.

export CLASSPATH=/path/to/bouncycastle/bcprov-jdk15on-155.jar
CERTSTORE=res/raw/mystore.bks
if [ -a $CERTSTORE ]; then
    rm $CERTSTORE || exit 1
fi
keytool \
      -import \
      -v \
      -trustcacerts \
      -alias 0 \
      -file <(openssl x509 -in mycert.pem) \
      -keystore $CERTSTORE \
      -storetype BKS \
      -provider org.bouncycastle.jce.provider.BouncyCastleProvider \
      -providerpath /path/to/bouncycastle/bcprov-jdk15on-155.jar \
      -storepass some-password

You'll notice that the above script places the result in res/raw/mystore.bks. Now you have a file that you'll load into your Android app that provides the missing certificate(s).

To do this, register your SSLSocketFactory for the SSL scheme:

final SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", createAdditionalCertsSSLSocketFactory(), 443));

// and then however you create your connection manager, I use ThreadSafeClientConnManager
final HttpParams params = new BasicHttpParams();
...
final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params,schemeRegistry);

To create your SSLSocketFactory:

protected org.apache.http.conn.ssl.SSLSocketFactory createAdditionalCertsSSLSocketFactory() {
    try {
        final KeyStore ks = KeyStore.getInstance("BKS");

        // the bks file we generated above
        final InputStream in = context.getResources().openRawResource( R.raw.mystore);  
        try {
            // don't forget to put the password used above in strings.xml/mystore_password
            ks.load(in, context.getString( R.string.mystore_password ).toCharArray());
        } finally {
            in.close();
        }

        return new AdditionalKeyStoresSSLSocketFactory(ks);

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

And finally, the AdditionalKeyStoresSSLSocketFactory code, which accepts your new KeyStore and checks if the built-in KeyStore fails to validate an SSL certificate:

/**
 * Allows you to trust certificates from additional KeyStores in addition to
 * the default KeyStore
 */
public class AdditionalKeyStoresSSLSocketFactory extends SSLSocketFactory {
    protected SSLContext sslContext = SSLContext.getInstance("TLS");

    public AdditionalKeyStoresSSLSocketFactory(KeyStore keyStore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(null, null, null, null, null, null);
        sslContext.init(null, new TrustManager[]{new AdditionalKeyStoresTrustManager(keyStore)}, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }



    /**
     * Based on http://download.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#X509TrustManager
     */
    public static class AdditionalKeyStoresTrustManager implements X509TrustManager {

        protected ArrayList<X509TrustManager> x509TrustManagers = new ArrayList<X509TrustManager>();


        protected AdditionalKeyStoresTrustManager(KeyStore... additionalkeyStores) {
            final ArrayList<TrustManagerFactory> factories = new ArrayList<TrustManagerFactory>();

            try {
                // The default Trustmanager with default keystore
                final TrustManagerFactory original = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                original.init((KeyStore) null);
                factories.add(original);

                for( KeyStore keyStore : additionalkeyStores ) {
                    final TrustManagerFactory additionalCerts = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    additionalCerts.init(keyStore);
                    factories.add(additionalCerts);
                }

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



            /*
             * Iterate over the returned trustmanagers, and hold on
             * to any that are X509TrustManagers
             */
            for (TrustManagerFactory tmf : factories)
                for( TrustManager tm : tmf.getTrustManagers() )
                    if (tm instanceof X509TrustManager)
                        x509TrustManagers.add( (X509TrustManager)tm );


            if( x509TrustManagers.size()==0 )
                throw new RuntimeException("Couldn't find any X509TrustManagers");

        }

        /*
         * Delegate to the default trust manager.
         */
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            final X509TrustManager defaultX509TrustManager = x509TrustManagers.get(0);
            defaultX509TrustManager.checkClientTrusted(chain, authType);
        }

        /*
         * Loop over the trustmanagers until we find one that accepts our server
         */
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            for( X509TrustManager tm : x509TrustManagers ) {
                try {
                    tm.checkServerTrusted(chain,authType);
                    return;
                } catch( CertificateException e ) {
                    // ignore
                }
            }
            throw new CertificateException();
        }

        public X509Certificate[] getAcceptedIssuers() {
            final ArrayList<X509Certificate> list = new ArrayList<X509Certificate>();
            for( X509TrustManager tm : x509TrustManagers )
                list.addAll(Arrays.asList(tm.getAcceptedIssuers()));
            return list.toArray(new X509Certificate[list.size()]);
        }
    }

}

Solution 3

Add this code before the HttpsURLConnection and it will be done. I got it.

private void trustEveryone() { 
    try { 
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){ 
                    public boolean verify(String hostname, SSLSession session) { 
                            return true; 
                    }}); 
            SSLContext context = SSLContext.getInstance("TLS"); 
            context.init(null, new X509TrustManager[]{new X509TrustManager(){ 
                    public void checkClientTrusted(X509Certificate[] chain, 
                                    String authType) throws CertificateException {} 
                    public void checkServerTrusted(X509Certificate[] chain, 
                                    String authType) throws CertificateException {} 
                    public X509Certificate[] getAcceptedIssuers() { 
                            return new X509Certificate[0]; 
                    }}}, new SecureRandom()); 
            HttpsURLConnection.setDefaultSSLSocketFactory( 
                            context.getSocketFactory()); 
    } catch (Exception e) { // should never happen 
            e.printStackTrace(); 
    } 
} 

I hope this helps you.

Solution 4

This is a bad idea. Trusting any certificate is only (very) slightly better than using no SSL at all. When you say "I want my client to accept any certificate (because I'm only ever pointing to one server)" you are assuming this means that somehow pointing to "one server" is safe, which it's not on a public network.

You are completely open to a man-in-the-middle attack by trusting any certificate. Anyone can proxy your connection by establishing a separate SSL connection with you and with the end server. The MITM then has access to your entire request and response. Unless you didn't really need SSL in the first place (your message has nothing sensitive, and doesn't do authentication) you shouldn't trust all certificates blindly.

You should consider adding the public cert to a jks using keytool, and using that to build your socket factory, such as this:

    KeyStore ks = KeyStore.getInstance("JKS");

    // get user password and file input stream
    char[] password = ("mykspassword")).toCharArray();
    ClassLoader cl = this.getClass().getClassLoader();
    InputStream stream = cl.getResourceAsStream("myjks.jks");
    ks.load(stream, password);
    stream.close();

    SSLContext sc = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");

    kmf.init(ks, password);
    tmf.init(ks);

    sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(),null);

    return sc.getSocketFactory();

This has one caveat to watch out for. The certificate will expire eventually, and the code will stop working at that time. You can easily determine when this will happen by looking at the cert.

Solution 5

You can disable HttpURLConnection SSL checking for testing purposes this way since API 8:

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
        httpsConn.setSSLSocketFactory(SSLCertificateSocketFactory.getInsecure(0, null));
        httpsConn.setHostnameVerifier(new AllowAllHostnameVerifier());
    }
Share:
725,425
harrisonlee
Author by

harrisonlee

iOS developer and designer.

Updated on October 18, 2021

Comments

  • harrisonlee
    harrisonlee over 2 years

    Recently posted a question regarding the HttpClient over Https (found here). I've made some headway, but I've run into new issues. As with my last problem, I can't seem to find an example anywhere that works for me. Basically, I want my client to accept any certificate (because I'm only ever pointing to one server) but I keep getting a javax.net.ssl.SSLException: Not trusted server certificate exception.

    So this is what I have:

    
        public void connect() throws A_WHOLE_BUNCH_OF_EXCEPTIONS {
    
            HttpPost post = new HttpPost(new URI(PROD_URL));
            post.setEntity(new StringEntity(BODY));
    
            KeyStore trusted = KeyStore.getInstance("BKS");
            trusted.load(null, "".toCharArray());
            SSLSocketFactory sslf = new SSLSocketFactory(trusted);
            sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme ("https", sslf, 443));
            SingleClientConnManager cm = new SingleClientConnManager(post.getParams(),
                    schemeRegistry);
    
            HttpClient client = new DefaultHttpClient(cm, post.getParams());
            HttpResponse result = client.execute(post);
        }
    

    And here's the error I'm getting:

        W/System.err(  901): javax.net.ssl.SSLException: Not trusted server certificate 
        W/System.err(  901):    at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:360) 
        W/System.err(  901):    at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:92) 
        W/System.err(  901):    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:321) 
        W/System.err(  901):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:129) 
        W/System.err(  901):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 
        W/System.err(  901):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 
        W/System.err(  901):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348) 
        W/System.err(  901):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 
        W/System.err(  901):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 
        W/System.err(  901):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 
        W/System.err(  901):    at me.harrisonlee.test.ssl.MainActivity.connect(MainActivity.java:129) 
        W/System.err(  901):    at me.harrisonlee.test.ssl.MainActivity.access$0(MainActivity.java:77) 
        W/System.err(  901):    at me.harrisonlee.test.ssl.MainActivity$2.run(MainActivity.java:49) 
        W/System.err(  901): Caused by: java.security.cert.CertificateException: java.security.InvalidAlgorithmParameterException: the trust anchors set is empty 
        W/System.err(  901):    at org.apache.harmony.xnet.provider.jsse.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:157) 
        W/System.err(  901):    at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:355) 
        W/System.err(  901):    ... 12 more 
        W/System.err(  901): Caused by: java.security.InvalidAlgorithmParameterException: the trust anchors set is empty 
        W/System.err(  901):    at java.security.cert.PKIXParameters.checkTrustAnchors(PKIXParameters.java:645) 
        W/System.err(  901):    at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:89) 
        W/System.err(  901):    at org.apache.harmony.xnet.provider.jsse.TrustManagerImpl.<init>(TrustManagerImpl.java:89) 
        W/System.err(  901):    at org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl.engineGetTrustManagers(TrustManagerFactoryImpl.java:134) 
        W/System.err(  901):    at javax.net.ssl.TrustManagerFactory.getTrustManagers(TrustManagerFactory.java:226)W/System.err(  901):     at org.apache.http.conn.ssl.SSLSocketFactory.createTrustManagers(SSLSocketFactory.java:263) 
        W/System.err(  901):    at org.apache.http.conn.ssl.SSLSocketFactory.<init>(SSLSocketFactory.java:190) 
        W/System.err(  901):    at org.apache.http.conn.ssl.SSLSocketFactory.<init>(SSLSocketFactory.java:216) 
        W/System.err(  901):    at me.harrisonlee.test.ssl.MainActivity.connect(MainActivity.java:107) 
        W/System.err(  901):    ... 2 more
    
  • yanokwa
    yanokwa almost 13 years
    this answer should probably note that trusting all certificates is horribly insecure and nullifies the entire purpose of ssl...
  • Brian Sweeney
    Brian Sweeney over 12 years
    well its still encrypted right? it just could be coming from anyone or being intercepted by anyone...
  • binarydreams
    binarydreams over 12 years
    @sweeney - Except that it's not guaranteed that you are talking to the server you think you are. If someone has mucked up a DNS server you could be communicating an encryption key with a hacker's server.
  • Matthias B
    Matthias B over 12 years
    how should that work? you reference registry before you even created it!
  • Matthias B
    Matthias B over 12 years
    Hey @emmby, this seems to be the perfect answer for my problem, but I still get no SSL connection. Can you please take a look at it? http://stackoverflow.com/questions/7822381/need-help-underst‌​anding-certificate-c‌​hains
  • Edwin Evans
    Edwin Evans over 12 years
    Thanks for the great writeup @emmby! I'm sometimes getting a really long delay and then a javax.net.ssl.SSLException: Read error:. Any idea? How can I set a timeout if the solution is same as stackoverflow.com/questions/5909308/android-2-3-4-ssl-proble‌​m?
  • Bruno
    Bruno about 12 years
    If you're not using client-certificate authentication, from the client side, you don't need a keymanager (use null in SSLContext.init). You should also use the default algorithms (KMF/TMF.getDefaultAlgorithm() ), instead of hard-coding SunX509` (more so because the default for TMF is actually PKIX on the Sun/Oracle JVM).
  • Someone Somewhere
    Someone Somewhere about 12 years
    Edwin, use HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_CONNECTION); and HttpConnectionParams.setSoTimeout(params, TIMEOUT_SOCKET); in my class the two values are Constants.
  • user207421
    user207421 about 12 years
    @sweeney In other words you are now liable to man-in-the-middle attacks. You should also note that that code doesn't meet the specification: check the Javadoc. getAcceptedIssuers() isn't allowed to return null.
  • Melvin Lai
    Melvin Lai about 12 years
    Yes, I have tested it on a Gingerbread. This is what I was looking for for a month!! Thanks @Daniel!!
  • Tim Bender
    Tim Bender about 12 years
    -1 Because it is a terrible idea to accept all certificates. It is too bad that there are so many blogs and tutorials that happily guide Java developers along the path of doing the wrong thing.
  • AndroidLearner
    AndroidLearner almost 12 years
    I only need to add .PFX Certificate File KeyStore using Android 2.3.3, Which piece of code from above solution will help me? Kindly help me i am working on this from 2 weeks and unable to understand anything.
  • dani herrera
    dani herrera over 11 years
    Exists a ready to use root certificates file? (like browsers do)
  • Rikki Tikki Tavi
    Rikki Tikki Tavi over 11 years
    @emmby, could you tell where should I put this code export CLASSPATH=bcprov-jdk16-145.jar CERTSTORE=res/raw/mystore.bks if [ -a $CERTSTORE ]; then rm $CERTSTORE || exit 1 fi keytool \ -import \ -v \ -trustcacerts \ -alias 0 \ -file <(openssl x509 -in mycert.pem) \ -keystore $CERTSTORE \ -storetype BKS \ -provider org.bouncycastle.jce.provider.BouncyCastleProvider \ -providerpath /usr/share/java/bcprov.jar \ -storepass some-password
  • Danation
    Danation over 11 years
    +1 Because I needed a quick solution for debugging purposes only. I would not use this in production due to the security concerns others have mentioned, but this was exactly what I needed for testing. Thank you!
  • Peterdk
    Peterdk over 11 years
    I implemented this, and it works great when I use the server certificate that I selfsigned. However, I wanted more flexibility and use a selfsigned rootCA, so that I can issue new certificates if needed (multiple domains etc). I created a new keystore with only that rootCA, but now on android 2.1 it complains with Not trusted server certificate. On higher versions (2.3/4) it verifies correct. Also in my browser it verifies ok. Any ideas?
  • Peterdk
    Peterdk over 11 years
    Well, it turns out it was due to using a snapshot with the emulator, making it's current date set to months earlier then the issues date of the cert. ... :)
  • OrhanC1
    OrhanC1 over 11 years
    Could someone point me to a tutorial where I can accept 1 trusted certificate without using some CLI?
  • Jason
    Jason over 11 years
    Is there any way to remove the password from the certificate store? The password isn't providing any protection anyway, the password ends up embedded in the binary.
  • user207421
    user207421 about 11 years
    Just repeats the same fallacious insecure non-solution that has already been discussed and dismissed in this thread.
  • Stevie
    Stevie about 11 years
    Please consider updating to point out that a badly configured server (missing the intermediate certificates) will also report "Not Trusted"? I sooo nearly went to the effort of creating a trust manager (and I bet many others have), when all I actually needed to do was fix the server configuration (see stackoverflow.com/questions/6825226/…).
  • Michael
    Michael almost 11 years
    I get this error. IOExceptionjavax.net.ssl.SSLPeerUnverifiedException: No peer certificate. This when doing the actual execute call on the HttpClient after the above setup is done.
  • Devgeeks
    Devgeeks over 10 years
    I used this as the basis for an app's mutual authentication by adding the presentation of a client certificate. This worked a treat in Android 4.x, but in 2.3.x I am getting a strange error: javax.net.ssl.SSLHandshakeException: org.bouncycastle.jce.exception.ExtCertPathValidatorException‌​: No valid policy tree found when one expected.. It seems to be related to the AdditionalKeyStoresSSLSocketFactory's AdditionalKeyStoresTrustManager. Worst bit is that googling the error returns next to nothing useful. Anyone have any ideas?
  • Ankit
    Ankit over 10 years
    Hi @Devgeeks, i am facing the same problem. May this developer.android.com/training/articles/… help you. If you already found this, please ignore this.
  • Ankit
    Ankit over 10 years
    Hey @emmby. I am using your solution in my app and using self signed certificate of my server but getting a CertificateException() in checkServerTrusted() method. I tried commenting that throw exception, and it works. if it does not validate my server cert then can i handle it in other way, Can you please guide what is the best solution in this case?
  • user207421
    user207421 over 10 years
    There is precisely zero point and some very real and extremely large risks in writing code that is only going to be used 'for testing'. I have a nasty suspicion, indeed it is practically certain, that a lot of these implementations find their way into production, and have yielded radically insecure systems as a result. If you don't code these security trapdoors into your system in the first place, that cannot happen.
  • Mike
    Mike over 10 years
    +1 for actually answering the question -1 because most classes in the client example are deprecated
  • Kevin
    Kevin over 10 years
    @Ankit, I am seeing the same behavior you suggest here after trying this solution. Can I please bother you for further information assuming you've moved past this by now? Thanks.
  • Ankit
    Ankit over 10 years
    @Kevin Yeah sure mate, tell me how may i help you?
  • Kevin
    Kevin over 10 years
    @Ankit Well, what was your problem? How did you get past the CertificateException that's thrown at the end of that method? Thanks.
  • Ankit
    Ankit over 10 years
    @Kevin in my case actual problem was from server side, they had not signed valid or proper certificate which i had to keep in my resources / assets, when they signed and gave me correct one, i used above solution and it worked for me. So in some cases self-signed certificates has some problem.
  • jww
    jww over 9 years
    The question was HttpClient and HTTPS; not OAuth for Android from a GitHub project.
  • jww
    jww over 9 years
    To quote EJP: "Just repeats the same fallacious insecure non-solution that has already been discussed and dismissed in this thread".
  • jww
    jww over 9 years
    To quote EJP: "Just repeats the same fallacious insecure non-solution that has already been discussed and dismissed in this thread".
  • jww
    jww over 9 years
    Once you verify the certificate this way on the first connection, what do you do with subsequent connections? Do you leverage the knowledge you gained from the first connection? What if a fake certificate with the same name is used on connection attempt 3?
  • Kachi
    Kachi over 9 years
    This should be marked as the right answer. One of the most thorough and well-written answers I've ever seen on SO. Dope
  • Ray Hunter
    Ray Hunter about 9 years
    I ran into issues with server CA cert misconfigured and needed a quick workaround to the SSL error "No peer certificate" and this worked like a charm.
  • Emil
    Emil about 9 years
    It seems that this ignores hostnames that don't match the certificate and accepts them even though it shouldn't.
  • ninjalj
    ninjalj almost 9 years
    @EJP: "a lot of these implementations find their way into production" Indeed. There is a research paper "The Most Dangerous Code in the World: Validating SSL Certificates in Non-Browser Software": cs.utexas.edu/~shmat/shmat_ccs12.pdf From the paper: We demonstrated that even applications that rely on standard SSL libraries [...] often perform SSL certificate validation incorrectly or not at all. These vulnerabilities are pervasive in critical software
  • inga
    inga almost 9 years
    This implementation doesn't work for API level 22 because org.apache.http.conn.ssl.SSLSocketFactory is deprecated. Do you have an updated solution?
  • Daniel
    Daniel almost 9 years
    @inga, the whole org.apache.http interfaces are deprecated. If you worry about that, you may try HttpURLConnection solution which I mentioned above for workaround.
  • zionpi
    zionpi over 8 years
    Where did myjks.jks comes from?
  • zackygaurav
    zackygaurav over 8 years
    org.apache.http.conn.ssl.AllowAllHostnameVerifier is deprecated.
  • Matt Friedman
    Matt Friedman over 8 years
    Using a custom trust strategy is the right answer. Thanks.
  • Shivam Nagpal
    Shivam Nagpal over 8 years
    I am still getting Handshake Exception and Certificate Exception
  • Petter Friberg
    Petter Friberg over 7 years
    Please don't add the same answer to multiple questions. Answer the best one and flag the rest as duplicates. See Is it acceptable to add a duplicate answer to several questions?
  • primehunter
    primehunter about 7 years
    Hello! I tried the code above for debug purpouses and got the javac error "The constructor DefaultHttpClient(ClientConnectionManager, HttpParams) is undefined" at <code>return new DefaultHttpClient(ccm, params);</code>. This is probably caused by jar version mismatch. So I tried different versions. (httpclient-4.5.3.jar, 4.1.2, 4.3-beta1 ...) No one of them worked :-( Any suggestion appreciated. Thank you for your time!
  • Steve Smith
    Steve Smith about 7 years
    This is the ideal Q&D solution. Short and "just works".
  • Levite
    Levite almost 7 years
    Perfect answer for testing purposes!!! And yes it is a bad idea to use in production, but come on ... that should be clear to everyone looking at the question title. It still answers it best/shortest/with the same (in)security level!
  • Dan
    Dan over 6 years
    @zionpi Generated using Java "keytool".
  • Mushtakim Ahmed Ansari
    Mushtakim Ahmed Ansari over 6 years
    what is new NoopHostnameVerifier() class?
  • raisercostin
    raisercostin over 6 years
    @MushtakimAhmedAnsari From docs: "The NO_OP HostnameVerifier essentially turns hostname verification off. This implementation is a no-op, and never throws the SSLException."
  • Ashish Jain
    Ashish Jain over 6 years
    Perfect code previously I was getting the same issue in Android 5.0 but not in above one but this code working for all OS version.
  • Abhay Dwivedi
    Abhay Dwivedi about 6 years
    Thanks for the great answer.This one should get more up votes.
  • DLight
    DLight about 6 years
    @zackygaurav According to the javadoc, AllowAllHostnameVerifier is replaced by NoopHostnameVerifier"
  • captainblack
    captainblack about 6 years
    now it says "javax.net.ssl.SSLHandshakeException: Handshake failed" :(
  • behelit
    behelit over 5 years
    How do I use it? or are you suggesting that simply having the class will override ssl certificate verifications?
  • raisercostin
    raisercostin over 5 years
    yes. that httpClient when used will not validate https certificates
  • user2028
    user2028 over 5 years
    Hello @yegor256, I am using this code, but still getting SSL handshake problem
  • Dika
    Dika about 5 years
    the idea is right. but I've got this error when I follow along this solution. error is: keytool error: java.lang.ClassNotFoundException: org.bouncycastle.jce.provider.BouncyCastleProvider . I solved it by using portecle jar to generate keystore.
  • user3738870
    user3738870 almost 5 years
    I think this answer is outdated. SSLSocketFactory is marked as deprecated in the apache package.
  • HaiNguyen
    HaiNguyen over 3 years
    How do you run "export " command from windows, I download bouncycastly jar file, do I need to install it to windows?
  • rogerdpack
    rogerdpack about 3 years
    Some of that stuff doesn't seem needed see stackoverflow.com/a/5297100/32453
  • Steven Love
    Steven Love almost 3 years
    This was simple and worked really well for me in contrast to many other answers. I was able to take the sslSocketFactory provided by this code and give it to a WebSocket library (nv-websocket-client) with .setSSLSocketFactory(). The only thing different for me was how to specify the depencency - my build.gradle file has dependencies{ implementation 'io.github.hakky54:sslcontext-kickstart:6.6.0' } instead of the XML provided in this answer. Thanks for your library!
  • Gaurav Mandlik
    Gaurav Mandlik over 2 years
    After adding this is app grant permission on playstore to upload ?