★38.HTTPS
2017-06-29 本文已影响0人
iDragonfly
流程图
前言
- 以下代码需要
catch
一堆异常,使用try-catch
所有的异常并打印即可。 - 可以使用工具类。
1. 创建KeyStore
方式一:通过证书
1. 创建Certificate
1. 获取公钥
方式一:从服务器获取公钥
InputStream pkStream = /* 服务器获取公钥输入流 */;
方式二:硬编码公钥
final String PUBLIC_KEY = "blablabla";
InputStream pkStream = new Buffer().writeUtf8(PUBLIC_KEY).inputStream();
2. 使用公钥生成Certificate
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Certificate certificate = certificateFactory.generateCertificate(pkStream);
Log.d("cert key", certificate.getPublicKey().toString());
2. 创建KeyStore
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("certificate", certificate);
方式二:通过本地KeyStore
-
KeyStore.load(..)
参数说明:-
InputStream
:KeyStore
文件输入流,可以把KeyStore
文件放入res/raw
目录中,通过R.raw.your_keystore_filename
获得。 -
char[]
:密码,用于解锁KeyStore
文件。
-
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
FileInputStream fileIS = getActivity().getApplicationContext()
.getResources().openRawResource(R.raw.your_keystore_filename);
char[] password = "Password".toCharArray();
keyStore.load(fileIS, password);
if (fileIS != null) fileIS.close();
2. 获取TrustManager[]
- 流程:
KeyStore
->TrustManagerFactory
->TrustManager[]
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
3. 获取KeyManager[]
- 流程:
KeyStore
->KeyManagerFactory
->KeyManager[]
String kmAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(kmAlgorithm);
keyManagerFactory.init(keyStore, "Password".toCharArray());
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
4. 创建SSLContext
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(keyManagers, trustManagers, new SecureRandom());
5. 创建SSLSocketFactory
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
6. HostnameVerifier
- 用于域名验证,确保域名没有被替换。
public static HostnameVerifier getHostnameVerifier(String[] myHostUrls) {
return (hostname, session) -> {
boolean isAcceptable = false;
for (String host : myHostUrls) {
if (host.equalsIgnoreCase(hostname)) {
isAcceptable = true;
}
}
return isAcceptable;
};
}
7. 从TrustManager[]
中获取X509TrustManager
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
8. 创建OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory, trustManager)
.hostnameVerifier(getHostnameVerifier(myHostUrls))
.build();