Android Https證書過期解決方案

??應(yīng)該有很多小伙伴遇到這樣一個(gè)問題,在線上已發(fā)布的app里,關(guān)于https的cer證書過期,從而導(dǎo)致app所有網(wǎng)絡(luò)請求失效無法使用。
??這個(gè)時(shí)候有人就要說了,應(yīng)急發(fā)布一個(gè)已更新最新cer證書的apk不就完事了么,其實(shí)沒那么簡單,iOS還好可以通過appstore提供的api查詢到新版本,但android就不一樣了,需要調(diào)用自己Server端提供的api接口查詢到新版本,并獲取apk下載路徑,問題是https都不能訪問了,如何請求到版本信息呢?
??博主在這里提供2種解決方案
??方案一:將版本信息接口讓后臺(tái)改成http(不推薦,后臺(tái)因素不可控),或者將本地https的設(shè)置一個(gè)不安全校驗(yàn)(推薦),代碼如下:

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())
                //設(shè)置不安全校驗(yàn)
                .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證書改成動(dòng)態(tài)讀取(以文件的方式從app沙盒里面讀取即可),在https證書即將過期時(shí),從服務(wù)器下載最新的cer證書更新到沙盒里面,App每次初始化網(wǎng)絡(luò)請求時(shí)讀取sdcard最新的證書文件,這樣App就永遠(yuǎn)不會(huì)出現(xiàn)https證書過期導(dǎo)致無法使用的問題,流程圖如下:

image.png

這里粘貼關(guān)鍵設(shè)置cer證書的代碼

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

總結(jié)一下,方案一需要App升級(jí)解決證書過期問題,方案二無需升級(jí)即可解決升級(jí)問題,小伙伴們,設(shè)置證書用哪種方式,心里有答案了吧。
代碼雖簡單,就當(dāng)做個(gè)筆記。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容