Trusting all certificates using HttpClient over HTTPS

后端 未结 21 2244
北恋
北恋 2020-11-21 04:50

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

21条回答
  •  攒了一身酷
    2020-11-21 05:13

    Trusting all certificates was no real alternative for me, so I did the following to get HttpsURLConnection to trust a new certificate (see also http://nelenkov.blogspot.jp/2011/12/using-custom-certificate-trust-store-on.html).

    1. Get the certificate; I got this done by exporting the certificate in Firefox (click on the little lock icon, get certificate details, click export), then used portecle to export a truststore (BKS).

    2. Load the Truststore from /res/raw/geotrust_cert.bks with the following code:

          final KeyStore trustStore = KeyStore.getInstance("BKS");
          final InputStream in = context.getResources().openRawResource(
                  R.raw.geotrust_cert);
          trustStore.load(in, null);
      
          final TrustManagerFactory tmf = TrustManagerFactory
                  .getInstance(TrustManagerFactory.getDefaultAlgorithm());
          tmf.init(trustStore);
      
          final SSLContext sslCtx = SSLContext.getInstance("TLS");
          sslCtx.init(null, tmf.getTrustManagers(),
                  new java.security.SecureRandom());
      
          HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx
                  .getSocketFactory());
      

提交回复
热议问题