Retrofit/OkHttp 设置 SSL Pinning

简介

众所周知,网络访问如果不做加密的话,请求数据很容易被抓包工具获取,从而造成安全隐患。所以,这里我们用到了 SSL Pining

使用

#方法一

OkHttp提供了一个 CertificatePinner 类可以方便的设置 SSL Pinning。

OkHttp

OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(new HttpLoggingInterceptor())
                .addInterceptor(intertor)
                .certificatePinner(pinner)
                .build();

getCertificataPinner

/**
 * SSL Pinning 获取证书
 * @return certificata
 */
public static CertificatePinner getCertificata() {

    Certificate ca = null;

    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = ZMApplication.getZMContext().getResources().openRawResource(R.raw.test);

        try {
            ca = cf.generateCertificate(caInput);
        } finally {
            caInput.close();
        }
    } catch (CertificateException | IOException e) {
        e.printStackTrace();
    }

    String certPin = "";
    if (ca != null) {
        certPin = CertificatePinner.pin(ca);
    }
    CertificatePinner certificatePinner = new CertificatePinner.Builder()
            .add(UrlConfig.RELEASE_BASE_URL, certPin)
            .build();

    return certificatePinner;
}

#方法二

创建一个只信任指定CA证书的 SSLSocketFactory 对象,注入到OkHttp中。这样OkHttp会使用注入的SSLSocketFactory去创建SSL Socket了

OkHttp

OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(new HttpLoggingInterceptor())
                .addInterceptor(intertor)
                .sslSocketFactory(sslFactory, trustManager)
                .build();

getSSLSocketFactory

SSLSocketFactory sslSocketFactory = null;
try {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); 

InputStream caInput = context.getResources().openRawResource(R.raw.ca);
Certificate ca = null;
try {
    ca = certificateFactory.generateCertificate(caInput);
} catch (CertificateException e) {
    e.printStrackTrace();
} finally {
    caInput.close();
}

String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
if (ca == null) {
    return null;
}
keyStore.setCertificateEntry("ca", ca);

String algorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(algorithm);
trustManagerFactory.init(keyStore);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

sslSocketFactory = sslContext.getSocketFactory();
} catch (CertificateException|IOException|KeyStoreException|NoSuchAlgorithmException|KeyManagementException e) {
e.printStackTrace();
}

参考

SSL Pinning on Android

你可能感兴趣的:(Retrofit/OkHttp 设置 SSL Pinning)