赞
踩
前言:
又有一段时间没更新咯,也是自己实在是懒。也想到发布文章的话不知道该发布什么。就时间间隔了这么长的时间,这段时间稍微没那么忙了就抽空写篇文章记录一下。也不是什么高科技高级技术。好了废话不多说直接来个正文吧
正文:
直接上代码
- /**
- * 关联Https请求验证证书
- *
- * @param okHttpClient
- */
- public OkHttpClient SSLContext(OkHttpClient.Builder okHttpClient){
- ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
- .allEnabledTlsVersions()
- .allEnabledCipherSuites()
- .build();
- try {
- //设置证书类型
- CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC");
- //打开放在main文件下的 assets 下的Http证书
- InputStream stream = getAssets().open("demo.crt");
- Certificate certificate = factory.generateCertificate(stream);
- //证书类型
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- //授信证书 , 授信证书密码(应该是服务端证书密码)
- keyStore.load(null, null);
- keyStore.setCertificateEntry("certificate",certificate);
-
- TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
- trustManagerFactory.init(keyStore);
-
- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
- //证书密码(应该是客户端证书密码)
- keyManagerFactory.init(keyStore, "555".toCharArray());
-
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(keyManagerFactory.getKeyManagers(),trustManagerFactory.getTrustManagers(),new SecureRandom());
- SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
-
- okHttpClient.connectionSpecs(Collections.singletonList(spec))
- .sslSocketFactory(sslSocketFactory, Platform.get().trustManager(sslSocketFactory))
- .hostnameVerifier(new HostnameVerifier() {
- @Override
- public boolean verify(String s, SSLSession sslSession) {
- return true;
- }
- });
-
- return okHttpClient.build();
-
- } catch (CertificateException e) {
- e.printStackTrace();
- } catch (NoSuchProviderException e) {
- e.printStackTrace();
- } catch (KeyStoreException e) {
- e.printStackTrace();
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- } catch (KeyManagementException e) {
- e.printStackTrace();
- } catch (UnrecoverableKeyException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
好了代码就是这一些,再加几条一些哥们写的.
这篇文章稍简单很多没有做过多的解释,大神勿喷
拓展:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。