簡介
眾所周知呵哨,網(wǎng)絡(luò)訪問如果不做加密的話,請求數(shù)據(jù)很容易被抓包工具獲取泳赋,從而造成安全隱患屿愚。所以汇跨,這里我們用到了 SSL Pining
使用
#方法一
OkHttp提供了一個 CertificatePinner
類可以方便的設(shè)置 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;
}
#方法二
創(chuàng)建一個只信任指定CA證書的 SSLSocketFactory
對象妆距,注入到OkHttp中扰法。這樣OkHttp會使用注入的SSLSocketFactory去創(chuàng)建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();
}