Android Https证书过期的两种解决方案

应该有很多小伙伴遇到这样一个问题,在线上已发布的app里,关于https的cer证书过期,从而导致app所有网络请求失效无法使用。

这个时候有人就要说了,应急发布一个已更新最新cer证书的apk不就完事了么,其实没那么简单,iOS还好可以通过appstore提供的api查询到新版本,但android就不一样了,需要调用自己Server端提供的api接口查询到新版本,并获取apk下载路径,问题是https都不能访问了,如何请求到版本信息呢?下面提供两种常见的解决方案:

方案一

将版本信息接口让后台改成http(不推荐,后台因素不可控),或者将本地https的设置一个不安全校验(推荐)。

private static OkHttpClient newOkHttpClient(int timeout){
 
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
 
        return new OkHttpClient.Builder()
                .addInterceptor(new RequestInfoInterceptor())
                //.addInterceptor(logging)
                .addNetworkInterceptor(new TokenHeaderInterceptor())
                .sslSocketFactory(Certificate.getSSLSocketFactory())
                //设置不安全校验
                .hostnameVerifier(Certificate.getUnSafeHostnameVerifier())
                .readTimeout(timeout, TimeUnit.SECONDS)
                .writeTimeout(timeout, TimeUnit.SECONDS)
                .build();
    }
 
    /**
     *获取HostnameVerifier 
     */
    public static HostnameVerifier getUnSafeHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }

方案二

将xxx.cer证书改成动态读取(以文件的方式从app沙盒里面读取即可),在https证书即将过期时,从服务器下载最新的cer证书更新到沙盒里面,App每次初始化网络请求时读取sdcard最新的证书文件,这样App就永远不会出现https证书过期导致无法使用的问题,流程图如下。

Android Https证书过期的两种解决方案_第1张图片

下面是一些关键的代码:

    private static OkHttpClient newOkHttpClient(int timeout){
 
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
 
        return new OkHttpClient.Builder()
                .addInterceptor(new RequestInfoInterceptor())
                //.addInterceptor(logging)
                .addNetworkInterceptor(new TokenHeaderInterceptor())
                .sslSocketFactory(Certificate.getSSLSocketFactory(BaseApplcation.myApp, new String[]{"/sdcard/xxx.cer"}))
                .hostnameVerifier(Certificate.getUnSafeHostnameVerifier())
                .readTimeout(timeout, TimeUnit.SECONDS)
                .writeTimeout(timeout, TimeUnit.SECONDS)
                .build();
    }
  
    /**
     * 带证书的,从本地文件读取
     * @param context
     * @param certificatesFiles  本地文件(通过下载到本地)
     * @return
     */
    public static SSLSocketFactory getSSLSocketFactory(Context context, String[] certificatesFiles) {
        if (context == null) {
            throw new NullPointerException("context == null");
        }
        CertificateFactory certificateFactory;
        try {
            certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);
 
            for (int i = 0; i < certificatesFiles.length; i++) {
                InputStream certificate = new FileInputStream(certificatesFiles[i]);
                keyStore.setCertificateEntry(String.valueOf(i), certificateFactory.generateCertificate(certificate));
 
                if (certificate != null) {
                    certificate.close();
                }
            }
            SSLContext sslContext = SSLContext.getInstance("TLS");
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
 
        }
        return null;
    }
 
  /**
     * 带证书的,从raw资源中读取
     * @param context
     * @param certificates  rawIds
     * @return
     */
    public static SSLSocketFactory getSSLSocketFactory(Context context, int[] certificates) {
        if (context == null) {
            throw new NullPointerException("context == null");
        }
        CertificateFactory certificateFactory;
        try {
            certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);
 
            for (int i = 0; i < certificates.length; i++) {
                InputStream certificate = context.getResources().openRawResource(certificates[i]);
                keyStore.setCertificateEntry(String.valueOf(i), certificateFactory.generateCertificate(certificate));
 
                if (certificate != null) {
                    certificate.close();
                }
            }
            SSLContext sslContext = SSLContext.getInstance("TLS");
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
 
        }
        return null;
    }

到此这篇关于Android Https证书过期的解决方案的文章就介绍到这了,更多相关Android Https证书过期内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(Android Https证书过期的两种解决方案)