Trusting all certificates using HttpClient over HTTPS

后端 未结 21 2235
北恋
北恋 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:10

    Daniel's answer was good except I had to change this code...

        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);
    

    to this code...

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        SchemeRegistry registry = ccm.getShemeRegistry()
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));
    

    to get it to work.

    0 讨论(0)
  • 2020-11-21 05:11

    Any body still struggling with StartCom SSL Certificates on Android 2.1 visit https://www.startssl.com/certs/ and download the ca.pem, now in the answer provided by @emmby replace

    `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`
    

    with

     `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 ca.pem) \
      -keystore $CERTSTORE \
      -storetype BKS \
      -provider org.bouncycastle.jce.provider.BouncyCastleProvider \
      -providerpath /usr/share/java/bcprov.jar \
      -storepass some-password`
    

    Should work out of the box. I was struggling it for over a day even after a perfect answer by @emmby.. Hope this helps someone...

    0 讨论(0)
  • 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());
      
    0 讨论(0)
  • 2020-11-21 05:14

    I'm looked response from "emmby" (answered Jun 16 '11 at 21:29), item #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 is a simplified implementation. Load the system keystore & merge with application keystore.

    public HttpClient getNewHttpClient() {
        try {
            InputStream in = null;
            // Load default system keystore
            KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType()); 
            try {
                in = new BufferedInputStream(new FileInputStream(System.getProperty("javax.net.ssl.trustStore"))); // Normally: "/system/etc/security/cacerts.bks"
                trusted.load(in, null); // no password is "changeit"
            } finally {
                if (in != null) {
                    in.close();
                    in = null;
                }
            }
    
            // Load application keystore & merge with system
            try {
                KeyStore appTrusted = KeyStore.getInstance("BKS"); 
                in = context.getResources().openRawResource(R.raw.mykeystore);
                appTrusted.load(in, null); // no password is "changeit"
                for (Enumeration<String> e = appTrusted.aliases(); e.hasMoreElements();) {
                    final String alias = e.nextElement();
                    final KeyStore.Entry entry = appTrusted.getEntry(alias, null);
                    trusted.setEntry(System.currentTimeMillis() + ":" + alias, entry, null);
                }
            } finally {
                if (in != null) {
                    in.close();
                    in = null;
                }
            }
    
            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    
            SSLSocketFactory sf = new SSLSocketFactory(trusted);
            sf.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    
            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();
        }
    }
    

    A simple mode to convert from JKS to BKS:

    keytool -importkeystore -destkeystore cacerts.bks -deststoretype BKS -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath bcprov-jdk16-141.jar -deststorepass changeit -srcstorepass changeit -srckeystore $JAVA_HOME/jre/lib/security/cacerts -srcstoretype JKS -noprompt
    

    *Note: In Android 4.0 (ICS) the Trust Store has changed, more info: http://nelenkov.blogspot.com.es/2011/12/ics-trust-store-implementation.html

    0 讨论(0)
  • 2020-11-21 05:15

    I used this and It works for me on all OS.

    /**
     * Disables the SSL certificate checking for new instances of {@link HttpsURLConnection} This has been created to
     * aid testing on a local box, not for use on production.
     */
    
    
    private static void disableSSLCertificateChecking() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
    
            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // Not implemented
            }
    
            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // Not implemented
            }
        } };
    
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
    
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
    
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:18

    work with all https

    httpClient = new DefaultHttpClient();
    
    SSLContext ctx = SSLContext.getInstance("TLS");
    X509TrustManager tm = new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }
    
        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }
    
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    
    ctx.init(null, new TrustManager[]{tm}, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    
    httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, ssf));
    
    0 讨论(0)
提交回复
热议问题