android turns on Https two-way authentication

Last article was written How to turn on https one-way authentication on Android The method of one-way authentication is that the client authenticates the identity of the server.Let's discuss how the server side authenticates the client.
Many people on the Internet say that Android only knows about certificates in BKS format, but after checking the official documents you will see them

So I'm using a PKCS12 certificate here.

openssl pkcs12 -export -out leikey1.p12 -inkey leikey.crt -in leichain.crt

Since the certificate is required for my entire system, I need to import it into the system, where I use a more clever method

void initSSL()  {
        try{
            InputStream kmin = this.getApplicationContext().getAssets().open("leikey1.p12");
            KeyStore kmkeyStore = KeyStore.getInstance("PKCS12");
            kmkeyStore.load(kmin,strKeyPWD.toCharArray());
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
            kmf.init(kmkeyStore, strKeyPWD.toCharArray());
            // Create an SSLContext that uses our TrustManager
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(kmf.getKeyManagers(), null, null);

            SSLContext.setDefault(context);
            Log.d(TAG, "init SSLContext for Https!");
        }catch(Exception e){
            e.printStackTrace();
        }
    }

Use it as follows:

void testConnect() {
        try{
            URL url = new URL(strUrl);
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);

            //Mainly add this line of code, our public and private keys are stored in the system, called through this line of code below.
            urlConnection.setSSLSocketFactory(SSLContext.getDefault().getSocketFactory());

            InputStream input = urlConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            Log.e(TAG, result.toString());
        }catch(Exception e){
            e.printStackTrace();
        }
    }

Reference Documents
https://developer.android.google.cn/reference/java/security/KeyStore.html
http://frank-zhu.github.io/android/2014/12/26/android-https-ssl/
http://blog.csdn.net/zww986736788/article/details/78425459
http://blog.csdn.net/Innost/article/details/44081147
http://blog.csdn.net/Innost/article/details/44199503

Keywords: Android OpenSSL Google Java

Added by hessian on Wed, 15 Jul 2020 18:28:14 +0300