How can I make Android Volley perform HTTPS request, using a certificate self-signed by an Unknown CA?

前端 未结 4 1431
无人共我
无人共我 2020-12-05 05:37

Before making the question, I found some links, which I checked, one by one, and none of them, gives me a solution:

  • well-kown CA HTTPS request
4条回答
  •  生来不讨喜
    2020-12-05 06:39

    you should accept all SSL certificates. To tell volley to trust your SSL, one option is the following code, which is based on https://developer.android.com/training/articles/security-ssl.html

    // trust the SSL certificate in our smarter server
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = ctx.getAssets().open("smarter_ssl.crt");
        Certificate ca;
        try {
            ca = cf.generateCertificate(caInput);
        } finally {
            caInput.close();
        }
    
        // Create a KeyStore containing our trusted CAs
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);
    
        // Create a TrustManager that trusts the CAs in our KeyStore
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);
        // Create an SSLContext that uses our TrustManager
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);
    
        SSLSocketFactory i = context.getSocketFactory();
    
        // Tell volley to use a SocketFactory from our SSLContext
        RequestQueue requestQueue = Volley.newRequestQueue(ctx.getApplicationContext(), new HurlStack(null, context.getSocketFactory()));
    

    to convert .pfx ssl certificates to .crt, follow: https://www.ibm.com/support/knowledgecenter/SSVP8U_9.7.0/com.ibm.drlive.doc/topics/r_extratsslcert.html

    The .crt file should be put in the assets folder as text.

提交回复
热议问题