有些时候,访问一些第三方接口可能需要双方携带特定的SSL证书进行验证,这边做个小计。

Okhttp的框架和其他框架类似,设置自定义的sslSocketFactory即可

            OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
            //支持HTTPS请求,证书验证
            clientBuilder.sslSocketFactory(createSSLSocketFactory(), new TrustAllCerts());
            clientBuilder.hostnameVerifier((hostname, session) -> true);
            clientBuilder.protocols(Collections.singletonList(Protocol.HTTP_1_1));

因为生成的证书有可能在根证书信任列表里,所以加载的时候,也可以进行忽略根证书颁发结构校验校验new TrustManager[]{new TrustAllCerts()}

    /**
     * 生成安全套接字工厂,用于https请求的证书验证
     */
    private SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            //将ca证书导入输入流
            byte[] byteKey = 证书流;
            InputStream fis = new ByteArrayInputStream(byteKey);
            char[] nPassword = 证书密码.toCharArray();
            SSLContext sc = SSLContext.getInstance("TLSv1.2");
            //keystore添加证书内容和密码
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(fis, nPassword);
            //key管理器工厂
            KeyManagerFactory keyManagerFactory =
                KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, nPassword);
            //构建一个ssl上下文,加入ca证书格式,与后台保持一致
            //参数,添加受信任证书和生成随机数
            sc.init(keyManagerFactory.getKeyManagers(), new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
            log.error("okHttp create SSL socketFactory failure:", e);
        }
        return ssfFactory;
    }
    
    
    /**
     * 用于信任所有证书
     * GlobalSign nv-sa 不在根证书
     */
    private class TrustAllCerts extends X509ExtendedTrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket)
            throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket)
            throws CertificateException {

        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine)
            throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine)
            throws CertificateException {

        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

下一篇