https certificate is used in Android

We use https to access the server when they are needed calibration certificate, when tested in order to facilitate all certificates default trust, but when the line would need to set a certificate, and a relatively simple way is the client built-in certificate, set frame to the network, such as OKHttp, so that the client will validate the server certificate is not consistent and the local certificate at the time of network access. Specific code as follows:

/**
     *
     * @param inputStream 本地证书的输入流
     * @return 创建SSLSocketFactory对象
     */
public static SSLSocketFactory getSocketFactory(InputStream inputStream){
        try {
            //1:创建CertificateFactory对象
            CertificateFactory cf = CertificateFactory.getInstance("X.509");

            //2:接收证书输入流,生成证书对象
            Certificate  ca = cf.generateCertificate(inputStream);

            //3:将证书对象放到keyStore中
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            trustStore.setCertificateEntry("ca", ca);

            //4:利用keyStore初始化TrustManagerFactory
            TrustManagerFactory trustManagerFactory =
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(trustStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

            //5:通过TrustManagerFactory初始化SSLContext
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagers, new SecureRandom());

            //6:设置给OKhttp,这样OKhttp就会自动校验证书,至于访问的服务器传输过来的证书和本地证书一直才能握手成功,
            // 可以通过单例模式在application中初始化
//            mOkHttpClient.setSslSocketFactory(sslContext.getSocketFactory());

            return sslContext.getSocketFactory();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return null;

    }

The above method creates SSLSocketFactory object, and then set to OKhttp to:

mOkHttpClient.setSslSocketFactory(socketFactory);

This logic is provided to initialize the calibration certificate is generally placed in the Application.

Because sometimes the certificates expire, so we can put our spouses certificate issued by root certificate into the apk to trust, so if in the future the certificate replaced or upgraded, with a long root certificate issued or used do not have to upgrade the client.

Here Insert Picture Description

I welcome the attention of the public number, we progress together

Guess you like

Origin blog.csdn.net/static_zh/article/details/95227585