Android如何给第三方联网请求框架配置https证书

1. 概述


这篇文章主要记录下自己在开发过程中遇到的需要给OKHttpUtils添加证书的问题,其实默认情况下绝大多数第三方联网请求框架都是支持https的SSL证书的,说白了,我们在开发过程中用的最多的还是OKHttp,因为Retrofit也可以说是对OKHttp进一步的封装。那么解析来我们就来看下,OKHttp是如何添加证书的,如果不是对http与https不是很清楚的,可以先看下我的这篇文章。

Http与Https区别

2. 具体实现


2.1>:运维会给你一个公钥,就是购买证书后的一个公钥,类似于下图所示:

Android如何给第三方联网请求框架配置https证书_第1张图片
图片.png

2.2>:自己定义一个工具类,用于添加https的证书,代码如下:

/**
 * Email: [email protected]
 * Created by JackChen 2018/4/13 11:50
 * Version 1.0
 * Params:
 * Description:   https添加证书工具类
*/

public class APIManager {

    private static final String CER_YILIAN = "-----BEGIN CERTIFICATE-----\n" +
            "MIIFqjCCBJKgAwIBAgIQBx+15z+1utfoVQez3qb4ADANBgkqhkiG9w0BAQsFADBe\n" +
           "MQswCQ"Fw0xODA0MDkwMDAwMDBaFw0xOTA0MDkxMjAwMDBaMBUxEzARBgNVBAMMCioudXBs\n" +
            "b28uYTFJTQUNBMjAxOC5jcmwwTAYDVR0gBEUwQzA3\n" +
            
            "AjAAMIIBAwYKKwYBBAHWeQIEAgSB9ASB8QDvAHUApLkJkLQYWBSHuxOizGdwCjw1\n" +
            
            "oSFEWyxDmV8NodSm2JLEsRppc7i4vTrchPS/75EkXS+AMKfNyrRDw4u0uS1+EZMl\n" +
            "P6Nl0JkGq1BJpvPhWCs=\n" +
            "-----END CERTIFICATE-----\n" +
            "-----BEGIN CERTIFICATE-----\n" +
            "MIIEsT
            
            "ysNyq0jEDQTkfa2pjmuWtMCNbBnhFXBYejfubIhaUbEv2FOQB3dCav+FPg5eEveX\n" +
            "TVyMnGo=\n" +
            "-----END CERTIFICATE-----";


    static private TrustManager[] createTrustManagers(InputStream... certificates){

        if (certificates == null || certificates.length <= 0) {
            return null;
        }

        try
        {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);

            int index = 0;
            for (InputStream certificate : certificates) {
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
                try {

                    if (certificate != null){
                        certificate.close();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());;
            trustManagerFactory.init(keyStore);

            return trustManagerFactory.getTrustManagers();

        } catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    static private HttpsUtils.SSLParams getSslSocketFactory(InputStream ... certificates){
        HttpsUtils.SSLParams sslParams = new HttpsUtils.SSLParams();

        try
        {
            TrustManager[] trustManagers = createTrustManagers(certificates);
            SSLContext sslContext = SSLContext.getInstance("TLS");

            final List x509trustManagers = new ArrayList();
            for(TrustManager tm : trustManagers){
                if(tm instanceof  X509TrustManager){
                    x509trustManagers.add((X509TrustManager)tm);
                }
            }

            X509TrustManager trustManager = new X509TrustManager() {

                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    for(X509TrustManager tm : x509trustManagers){
                        tm.checkServerTrusted(x509Certificates, s);
                    }
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            };

            sslContext.init(null, new TrustManager[]{trustManager},null);
            sslParams.sSLSocketFactory = sslContext.getSocketFactory();
            sslParams.trustManager = trustManager;
            return sslParams;

        } catch (NoSuchAlgorithmException e) {
            throw new AssertionError(e);
        } catch (KeyManagementException e) {
            throw new AssertionError(e);
        }
    }


    /**
     * OKHttp添加证书
     * @return
     */
    protected static OkHttpClient CheckOkhttps() {

        try {
//             HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(new InputStream[]{new Buffer().writeUtf8(CER_YILIAN).inputStream()}, null, null);
            HttpsUtils.SSLParams sslParams = getSslSocketFactory(new ByteArrayInputStream(CER_YILIAN.getBytes("UTF-8")));
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(60000L, TimeUnit.MILLISECONDS)
                    .readTimeout(60000L, TimeUnit.MILLISECONDS)
                    .addInterceptor(new LoggerInterceptor("TAG"))
                    .hostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    })
                    .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                    .build();
            OkHttpUtils.initClient(okHttpClient);
            return okHttpClient;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
}

2.3>:然后在BaseApplication中调用 CheckOkhttps()方法即可,表示给OKHttp添加证书,代码如下:

public class BaseApplication extends Application {
 @Override
    public void onCreate() {
        super.onCreate();
        CheckOkhttps() ;
}

以上就是给OKHttp添加https证书,当然对于给OKHttp添加证书还有很多种方法,同时也还有很多场景,我这里只是简单的总结一下,如果还想看一下其他具体的方法,可以点击下边链接就ok。

https://blog.csdn.net/lmj623565791/article/details/48129405

你可能感兴趣的:(Android如何给第三方联网请求框架配置https证书)