★38.HTTPS

2017-06-29  本文已影响0人  iDragonfly

流程图

前言

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

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[]

String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

3. 获取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();
上一篇下一篇

猜你喜欢

热点阅读