关于OkHttp代码设置证书的记录

public void initSslContext(InputStream... certificates) {
        try {
            //certificates-证书输入流
            //服务端配置的信任证书
            //0-用CertificateFactory将流得到Certificate
            //1-将certificates 放入serviceKeyStore内(hashTable方式存放)
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore serviceKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            serviceKeyStore.load(null);
            int index = 0;
            for (InputStream certificate : certificates) {
                String certificateAlias = Integer.toString(index++);
                serviceKeyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));

                try {
                    if (certificate != null) {
                        certificate.close();
                    }
                } catch (IOException e) {
                }
            }

            //2-用serviceKeyStore初始化TrustManagerFactory
            TrustManagerFactory trustManagerFactory =
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(serviceKeyStore);

            //3-双向的话 客户端的bks - 这里是per->jsk->bks
            //123456:client_bks_password
//            KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
//            clientKeyStore.load(mContext.getAssets().open("test.jks"), "123456".toCharArray());
            KeyStore clientKeyStore = KeyStore.getInstance("BKS");
            clientKeyStore.load(mContext.getAssets().open("test.bks"), "123456".toCharArray());
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(clientKeyStore, "123456".toCharArray());

            //4-初始化SSLContext
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init
                    (
                            keyManagerFactory.getKeyManagers(),
                            trustManagerFactory.getTrustManagers(),
                            new SecureRandom()
                    );
            //5-OkHttpClient设置SslSocketFactory
//            OkHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
        } catch (Exception e) {
        }

    }

 

你可能感兴趣的:(https,android)