Self-signed certificate and loopj for Android

前端 未结 6 449
太阳男子
太阳男子 2021-01-30 15:08

I\'m trying to use loopj for making async HTTP requests. Works great, except when I try to access https site with self-signed cert. I get

6条回答
  •  广开言路
    2021-01-30 16:01

    As explained in many places simply bypassing verification of the certificates is wrong on so many levels. Do not do that!

    What you should do instead is to create .bks file from your cert(for that purpose you gonna need 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
    

    Next place your newly created outputname.bks inside res/raw folder.

    Create helper function(it could be inside own class or whatever you like):

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

    And last but not least, set your AsyncHttpClient to use the new socket factory:

    AsyncHttpClient client = new AsyncHttpClient();
    client.setSSLSocketFactory(getSocketFactory(context));
    

提交回复
热议问题