14

我正在尝试使用loopj发出异步 HTTP请求。效果很好,除非我尝试使用自签名证书访问 https 站点。我明白了

javax.net.ssl.SSLPeerUnverifiedException: No peer certificate.

我猜默认的ssl选项可以覆盖 usingsetSSLSocketFactory(SSLSocketFactory sslSocketFactory)方法,但我不知道该怎么做,或者它可能根本不是正确的方法。

请建议我该如何解决这个问题?

4

6 回答 6

41

您所做的几乎与此处为 HttpClient 解释的完全相同,只是稍微简单一点 -使用 HttpClient over HTTPS 信任所有证书

创建一个自定义类:

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

然后,当您创建客户端实例时:

try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);
      sf = new MySSLSocketFactory(trustStore);
      sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      client.setSSLSocketFactory(sf);   
    }
    catch (Exception e) {   
    }
于 2012-08-22T23:34:32.173 回答
9

您可以使用构造函数 AsyncHttpClient(boolean fixNoHttpResponseException, int httpPort, int httpsPort)。从版本 loopj 库 1.4.4 和更大。例如

mClient = new AsyncHttpClient(true, 80, 443);

并且您会在详细日志中收到向 logcat 发出的警告消息。

Beware! Using the fix is insecure, as it doesn't verify SSL certificates.
于 2014-07-29T14:55:51.743 回答
6

更简单的方法是在 loopj 中使用内置的 MySSLSocketFactory,因此您不必创建另一个类

try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        client.setSSLSocketFactory(sf);
}
catch (Exception e) {}
于 2015-01-29T18:38:25.863 回答
6

正如许多地方所解释的那样,简单地绕过证书验证在很多层面上都是错误的。不要那样做!

你应该做的是.bks从你的证书创建文件(为此你需要Bouncy Castle):

keytool -importcert -v -trustcacerts -file "path/to/certfile/certfile.crt" -alias IntermediateCA -keystore "outputname.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "path/to/bouncycastle/bcprov-jdk15on-154.jar" -storetype BKS -storepass atleastsix

接下来放置新创建的outputname.bks内部res/raw文件夹。

创建辅助函数(它可以在自己的类中或您喜欢的任何内容中):

private static SSLSocketFactory getSocketFactory(Context ctx) {
        try {
            // Get an instance of the Bouncy Castle KeyStore format
            KeyStore trusted = KeyStore.getInstance("BKS");
            // Get the raw resource, which contains the keystore with
            // your trusted certificates (root and any intermediate certs)
            InputStream in = ctx.getResources().openRawResource(R.raw.outputname); //name of your keystore file here
            try {
                // Initialize the keystore with the provided trusted certificates
                // Provide the password of the keystore
                trusted.load(in, "atleastsix".toCharArray());
            } finally {
                in.close();
            }
            // Pass the keystore to the SSLSocketFactory. The factory is responsible
            // for the verification of the server certificate.
            SSLSocketFactory sf = new SSLSocketFactory(trusted);
            // Hostname verification from certificate
            // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
            sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); // This can be changed to less stricter verifiers, according to need
            return sf;
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }

最后但同样重要的是,设置您AsyncHttpClient使用新的套接字工厂:

AsyncHttpClient client = new AsyncHttpClient();
client.setSSLSocketFactory(getSocketFactory(context));
于 2016-03-07T19:40:39.607 回答
0

在两个文档HttpsUrlConnectionPortecleHttps的帮助下,certificate我已经成功地完成了它。

于 2012-07-20T05:29:27.960 回答
0

不要 NUKE 所有 SSL 证书.. 信任所有证书是一种不好的做法!!!

  • 仅接受您的 SSL 证书。

看看我的解决方案。此 Gist 中的一些内容可以帮助您了解如何执行此操作。

OBS.:我正在使用Android Volley

https://gist.github.com/ivanlmj/f11fb50d35fa1f2b9698bfb06aedcbcd

于 2016-10-18T18:15:43.780 回答