Https系列之四:https的SSL證書在Android端基於okhttp,Retrofit的使用

来源:http://www.cnblogs.com/garyyan/archive/2017/09/28/7605097.html
-Advertisement-
Play Games

Https系列會在下麵幾篇文章中分別作介紹: 一:https的簡單介紹及SSL證書的生成二:https的SSL證書在伺服器端的部署,基於tomcat,spring boot三:讓伺服器同時支持http、https,基於spring boot四:https的SSL證書在Android端基於okhttp ...


Https系列會在下麵幾篇文章中分別作介紹:

一:https的簡單介紹及SSL證書的生成
二:https的SSL證書在伺服器端的部署,基於tomcat,spring boot
三:讓伺服器同時支持http、https,基於spring boot
四:https的SSL證書在Android端基於okhttp,Retrofit的使用

所有文章會優先在:
微信公眾號“顏家大少”中發佈
轉載請標明出處


先來回顧一下

前面已分別介紹了https,SSL證書的生成,並完成了伺服器端的https的部署
並提到一個重要的用於客戶端的證書:公鑰證書
在前面文章中,自簽名SSL證書對應的公鑰證書為:mycer.cer(當然這名字是自己隨便定的);在阿裡雲申請的CA證書中對應的公鑰證書為:*.pem
如果有不清楚的,請看我之前介紹過的文章

Android自帶的可信任的CA公鑰證書

還要說明一下,Android系統有自帶的安卓認可的證書頒發機構(如:Wosign)頒發的可信任的CA公鑰證書,大概有100多個,
可自己查看,各個手機的查看方法可能不一樣,在我的手機中,能在下麵的位置中找到:
“設置”->”更多設置“->”系統安全“->”信任的憑據”
也就是說,如果你伺服器的證書是安卓認可的證書頒發機構頒發的,那麼你並不需要在Android端額外安裝公鑰證書,否則,你就需要安裝。
註:在不同版本的Android系統上,可信任的CA證書可能是不一樣的,如果你擔心在別人的Android系統上可能此CA證書不被信任,那你統一都安裝也是沒問題的
我在阿裡雲上申請的免費型DV SSL證書,是屬於安卓認可的證書頒發機構頒發的,不需要額外安裝,當然我們的自簽名證書,是必需要安裝的
其實我在測試的過程中,把自簽名證書和阿裡雲上申請的免費型DV SSL證書都用同樣的方法安裝了,都是OK的

我們下麵就開始基於okhttp來安裝公鑰證書了

先看看我的okhttp和retrofit的gradle版本

compile 'com.squareup.okhttp3:okhttp:3.8.1'
compile 'com.squareup.retrofit2:retrofit:2.3.0'

增加一個OkhttpManager類

統一處理OkHttpClient的證書,完整的代碼如下:

import android.content.Context;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.Collection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;

public class OkhttpManager {
    static private OkhttpManager mOkhttpManager=null;
    private InputStream mTrustrCertificate;
    static public OkhttpManager getInstance()
    {
        if(mOkhttpManager==null)
        {
            mOkhttpManager=new OkhttpManager();
        }
        return mOkhttpManager;
    }

    private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
        try {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            InputStream in = null; // By convention, 'null' creates an empty key store.
            keyStore.load(in, password);
            return keyStore;
        } catch (IOException e) {
            throw new AssertionError(e);
        }
    }

    private X509TrustManager trustManagerForCertificates(InputStream in)
            throws GeneralSecurityException {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
        if (certificates.isEmpty()) {
            throw new IllegalArgumentException("expected non-empty set of trusted certificates");
        }

        // Put the certificates a key store.
        char[] password = "password".toCharArray(); // Any password will work.
        KeyStore keyStore = newEmptyKeyStore(password);
        int index = 0;
        for (Certificate certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificate);
        }

        // Use it to build an X509 trust manager.
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
        }
        return (X509TrustManager) trustManagers[0];
    }

    public void setTrustrCertificates(InputStream in)
    {
        mTrustrCertificate=in;
    }

    public InputStream getTrustrCertificates()
    {
        return mTrustrCertificate;
    }

    public OkHttpClient build()
    {
        OkHttpClient okHttpClient=null;
        if(getTrustrCertificates()!=null)
        {
            X509TrustManager trustManager;
            SSLSocketFactory sslSocketFactory;
            try {
                trustManager = trustManagerForCertificates(getTrustrCertificates());
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, new TrustManager[] { trustManager }, null);
                sslSocketFactory = sslContext.getSocketFactory();
            } catch (GeneralSecurityException e) {
                throw new RuntimeException(e);
            }
            okHttpClient=new OkHttpClient.Builder()
                    .sslSocketFactory(sslSocketFactory, trustManager)
                    .build();
        }
        else
        {
            okHttpClient=new OkHttpClient.Builder()
                                         .build();
        }
        return okHttpClient;
    }

}

代碼解釋

代碼不少,其實最核心的代碼為:

public OkHttpClient build()
{
.......
 trustManager = trustManagerForCertificates(getTrustrCertificates());
 .......
  okHttpClient=new OkHttpClient.Builder()
                    .sslSocketFactory(sslSocketFactory, trustManager)
                    .build();
 ..........
 return okHttpClient;
}

也就是通過

void setTrustrCertificates(InputStream in)

把自己的證書對應的文件set進去

然後通過

trustManager =trustManagerForCertificates(getTrustrCertificates());

okHttpClient=new OkHttpClient.Builder()
                    .sslSocketFactory(sslSocketFactory, trustManager)
                    .build();

就能生成安裝好了可信任證書的okHttpClient

OkhttpManager說完了,接下來,就是:

Activity中使用OkhttpManager

1:先把公鑰證書文件(如:自簽名的mycer.cer或CA證書的:*.pem)放到assets下,
如果使用AndroidStudio的同學,可能沒有assets文件夾,自己建此文件夾,如我的為:app\src\main\assets

2:直接貼Activity主要的代碼:

public class MyActivity extends AppCompatActivity {
@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       try {
            OkhttpManager.getInstance().setTrustrCertificates(getAssets().open("mycer.cer");
            OkHttpClient mOkhttpClient= OkhttpManager.getInstance().build();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

簡單吧,主要代碼就那兩句,就生成了已安裝公鑰證書”mycer.cer”的mOkhttpClient
接下來的mOkhttpClient怎樣使用,大家都應該清楚了吧,如果不清楚只能看OkHttpClient的基礎內容了

好了,OkHttpClient搞掂了

接下來就到Retrofit了

大家應該知到Retrofit預設是以OkHttpClient來作為傳輸的,既然OkHttpClient搞掂了,那Retrofit就簡單了
還是直接貼代碼:

 Retrofit retrofit = new Retrofit.Builder()
                .client(mOkhttpClient)
                .baseUrl("your_serverl_url")
                .build();

看,只需在Retrofit中多加一句

.client(mOkhttpClient)

就把已安裝了證書的mOkhttpClient作為Retrofit的傳輸了


更多內容,請關註微信公眾號:顏家大少
這裡寫圖片描述


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 使用Grunt構建項目涉及磁碟操作,構建效率較低,因此,基於流的Gulp應運而生。本節通過一個例子,介紹如何利用Gulp構建一個ECMAScript 6和Sass應用。 ...
  • redux原理 某公司有物流(actionType)、電商(actionType)、廣告(actionType)3塊業務,在公司財務系統(state)統一記錄著三塊業務分別賺取到的資金。某天,電商業務在公司電商平臺銷售了價值100w的商品(action),賺取到的資金通過發票(dispatch)的形 ...
  • 1、webstrom 11.0.3下載地址1:http://pan.baidu.com/s/1kVQjcwf 密碼:uggr 下載地址2:http://pan.baidu.com/s/1kVQjcwf,點擊DOWNLOAD即可下載 2、webstrom11激活 選擇“license server” ...
  • 網頁title旁邊的小圖片設置,圖片格式必須是.ico ...
  • 一、jQuery 中的常用函數 1) $.map(Array,fn); 對數組中的每個元素,都用fn進行處理,fn將處理後的結果返回,最後得到一個數組 2) $.each(Array,fn); 對數組中的每個元素,調用fn這個函數進行處理,但是,沒有返回值,比上例更常用 二、jQuery 對象和Do ...
  • 最近在前端開發中,遇到一個JavaScript 的問題。 用Chrome,Firefox,運行結果正常。但是在IE裡面確出現了"對象不支持find屬性或方法"的錯誤. 看了下官方文檔才發現他是不支持IE的。https://developer.mozilla.org/en-US/docs/Web/Ja ...
  • 轉自博客園: 現在有一個數據,需要你渲染出對應的列表出來: var data = [ {"id":1}, {"id":2}, {"id":3}, {"id":4}, ]; var str="<ul>"; data.forEach(function(v,i){ str+="<li><span>"+v. ...
  • XMLHttpRequest對象 一、XMLHttpRequest對象 1.Ajax能夠是實現非同步傳輸,所依賴的就是JavaScript中的XMLHttpRequest 2.XMLHttpRequest對象是XMLHttp組件的對象,它是一個抽象對象,允許腳本從伺服器獲取返回的eXML數據或將數據發 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...