accept self-signed SSL Certificates-> where to set default TrustManager

后端 未结 1 1471
一个人的身影
一个人的身影 2021-02-06 11:51

First I had to admit that I know that accepting all certs can be considered as having no security. We have \"real\" Certs but only on our live systems. The certs on our test sys

相关标签:
1条回答
  • 2021-02-06 12:06

    No, it doesn't force you to disable validation, it forces you to implement validation properly. Do not blindly accept all certificates. And no, your case is not any different, you just need to trust a certificate that Android doesn't trust by default.

    You are using HttpClient, so the APIs for setting the trust manager are somewhat different than HttpsURLConnection, but the procedure is the same:

    1. Load a keystore file with trusted certificates (your server's self-signed certificates)
    2. Initialize a KeyStore with it.
    3. Create a SocketFactory using the KeyStore from 2.
    4. Set your HTTP client library to use it when creating SSL sockets.

    This is described in Android's documentation: http://developer.android.com/reference/org/apache/http/conn/ssl/SSLSocketFactory.html

    A more detailed article on the subject, shows how to create the trust store file: http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html

    Some background information and example code: http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html

    This is the code you need to initialize HttpClient:

    KeyStore localTrustStore = KeyStore.getInstance("BKS");
    InputStream in = getResources().openRawResource(R.raw.mytruststore);
    localTrustStore.load(in, TRUSTSTORE_PASSWORD.toCharArray());
    
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), 80));
    SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore);
    schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
    HttpParams params = new BasicHttpParams();
    ClientConnectionManager cm = 
        new ThreadSafeClientConnManager(params, schemeRegistry);
    
    HttpClient client = new DefaultHttpClient(cm, params); 
    

    At this point, you have no excuses for trusting all certificates. If you do, it all on you :)

    0 讨论(0)
提交回复
热议问题