地址:http://blog.csdn.net/doubleping/article/details/53331864

调用new CustomTrust() 即可产生OkHttpClient

关键点:
1、将pem证书放入Raw或者assets目录。
2、证书的KeyStore读取方式。
3、HostnameVerifier过滤验证。

讲解: Pem 有多个 Certificate ,用CertificateFactory 读取 inputstream 为context.getResources().openRawResource(R.raw.a223)

1、证书读取详细:

   private SSLContext trustManagerForCertificates(InputStream in)throws GeneralSecurityException, IOException {CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);if (certificates.isEmpty()) {throw new IllegalArgumentException("expected non-empty set of trusted certificates");}// Put the certificates a key store.char[] password = CLIENT_KET_PASSWORD.toCharArray(); // Any password will work.KeyStore keyStore = newEmptyKeyStore(password);int index = 0;for (Certificate certificate : certificates) {String certificateAlias = Integer.toString(index++);keyStore.setCertificateEntry(certificateAlias, certificate);}//  keyStore.load(in,CLIENT_KET_PASSWORD.toCharArray());// Use it to build an X509 trust manager.KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());keyManagerFactory.init(keyStore, password);TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());trustManagerFactory.init(keyStore);TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {throw new IllegalStateException("Unexpected default trust managers:"+ Arrays.toString(trustManagers));}SSLContext ssContext = SSLContext.getInstance("SSL");ssContext.init(keyManagerFactory.getKeyManagers(),trustManagers,null);//return (X509TrustManager) trustManagers[0];return  ssContext;}private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {try {KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());InputStream in = null; // By convention, 'null' creates an empty key store.keyStore.load(in, password);return keyStore;} catch (IOException e) {throw new AssertionError(e);}}

2、SSLContext创建

关键:必须重写 HostnameVerifier 不然会出现javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated.错误,因为OKhttp 拥有默认的验证。

try {//  trustManager = trustManagerForCertificates(trustedCertificatesInputStream());SSLContext sslContext =  trustManagerForCertificates(trustedCertificatesInputStream()); //SSLContext.getInstance("TLS");sslSocketFactory = sslContext.getSocketFactory();} catch (GeneralSecurityException e) {throw new RuntimeException(e);} catch (IOException e) {e.printStackTrace();}client = new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory).hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}}).build();

所有代码:将证书路径改动一下就可以直接使用了


import android.content.Context;import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.Collection;import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;import okhttp3.CertificatePinner;
import okhttp3.OkHttpClient;public final class CustomTrust {public static final String tag = "CustomTrust";private static final String CLIENT_KET_PASSWORD = "2342342342344433";public final OkHttpClient client;Context context;public CustomTrust(Context context)  {this.context = context;X509TrustManager trustManager;SSLSocketFactory sslSocketFactory=null;try {//  trustManager = trustManagerForCertificates(trustedCertificatesInputStream());SSLContext sslContext =  trustManagerForCertificates(trustedCertificatesInputStream()); //SSLContext.getInstance("TLS");sslSocketFactory = sslContext.getSocketFactory();} catch (GeneralSecurityException e) {throw new RuntimeException(e);} catch (IOException e) {e.printStackTrace();}client = new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory).hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}}).build();}/*** Returns an input stream containing one or more certificate PEM files. This implementation just* embeds the PEM files in Java strings; most applications will instead read this from a resource* file that gets bundled with the application.*/private InputStream trustedCertificatesInputStream() {// PEM files for root certificates of Comodo and Entrust. These two CAs are sufficient to view// https://publicobject.com (Comodo) and https://squareup.com (Entrust). But they aren't// sufficient to connect to most HTTPS sites including https://godaddy.com and https://visa.com.// Typically developers will need to get a PEM file from their organization's TLS administrator.return context.getResources().openRawResource(R.raw.qwww2) ;/*return new Buffer().writeUtf8(comodoRsaCertificationAuthority).writeUtf8(entrustRootCertificateAuthority).inputStream();*/}/*** Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose* certificates have not been signed by these certificates will fail with a {@code* SSLHandshakeException}.** <p>This can be used to replace the host platform's built-in trusted certificates with a custom* set. This is useful in development where certificate authority-trusted certificates aren't* available. Or in production, to avoid reliance on third-party certificate authorities.** <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using* the host platform's built-in trust store.** <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>** <p>Relying on your own trusted certificates limits your server team's ability to update their* TLS certificates. By installing a specific set of trusted certificates, you take on additional* operational complexity and limit your ability to migrate between certificate authorities. Do* not use custom trusted certificates in production without the blessing of your server's TLS* administrator.*/private SSLContext trustManagerForCertificates(InputStream in)throws GeneralSecurityException, IOException {CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);if (certificates.isEmpty()) {throw new IllegalArgumentException("expected non-empty set of trusted certificates");}// Put the certificates a key store.char[] password = CLIENT_KET_PASSWORD.toCharArray(); // Any password will work.KeyStore keyStore = newEmptyKeyStore(password);int index = 0;for (Certificate certificate : certificates) {String certificateAlias = Integer.toString(index++);keyStore.setCertificateEntry(certificateAlias, certificate);}//  keyStore.load(in,CLIENT_KET_PASSWORD.toCharArray());// Use it to build an X509 trust manager.KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());keyManagerFactory.init(keyStore, password);TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());trustManagerFactory.init(keyStore);TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {throw new IllegalStateException("Unexpected default trust managers:"+ Arrays.toString(trustManagers));}SSLContext ssContext = SSLContext.getInstance("SSL");ssContext.init(keyManagerFactory.getKeyManagers(),trustManagers,null);//return (X509TrustManager) trustManagers[0];return  ssContext;}private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {try {KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());InputStream in = null; // By convention, 'null' creates an empty key store.keyStore.load(in, password);return keyStore;} catch (IOException e) {throw new AssertionError(e);}}//  public static void main(String... args) throws Exception {
//    new CustomTrust().run();
//  }
}

java Android OKHttp HTTPS 请求证书验证 PEM证书(1)相关推荐

  1. android https请求证书过滤白名单,Android处理https请求的证书问题

    android中对部分站点发送https请求会报错,原因是该站点的证书时自定义的,而非官方的,android手机不信任其证书,为了解决这个问题,一般有两种解决方案 忽略证书验证 下载证书到本地,添加到 ...

  2. 青花瓷抓包工具如何对Android手机https请求抓包及华为手机安装Charles证书方法详解!

    网上搜索了很多文档,这两篇是写的比较全面的,整个流程看完,你就会安装使用了! 参考:windows下使用Charles工具如何对android手机https请求进行抓包 参考:Android安装Cha ...

  3. JAVA实现发送HTTPS请求(SSL双向认证)

    一.项目背景 Java项目需要作为客户端发起HTTPS请求访问服务端,并且需要携带证书进行SSL双向认证,当前提供的证书相关文件有:ca.crt.ca.key.client.crt.client.ke ...

  4. Android okHttp网络请求之缓存控制Cache-Control

    前言: 前面的学习基本上已经可以完成开发需求了,但是在项目中有时会遇到对请求做个缓存,当没网络的时候优先加载本地缓存,基于这个需求我们来学习一直okHttp的Cache-Control. okHttp ...

  5. jks证书转为pem证书,TrustedCertEntry not supported的解决办法

    最近测试脚本的语言用ruby写了,因为涉及到证书通讯,而公司服务证书生成的是jks证书,而ruby中用的证书为openssl x509 的pem格式. 从网上看到先把jks证书转为p12证书,然后再从 ...

  6. java在访问https资源时,忽略证书信任问题

    java程序在访问https资源时,出现报错 sun.security.validator.ValidatorException: PKIX path building failed: sun.sec ...

  7. java ocsp校验_Nginx使用OCSP验证客户端证书

    此前,Nginx只支持OSCP验证服务器证书. 目前,Nginx 1.19.0+已经支持使用OSCP验证客户端证书:https://trac.nginx.org/nginx/ticket/1534 有 ...

  8. Android 手机设置 Charles 代理,pem 证书安装不上?

    「注意文章红字部分,100% 解决问题」 最近在家办公,需要远程链接内网调试,but 公司的 vpn 账号只能单设备登录,只好使用手机代理了. 本文使用的代理是 Charles,具体 Charles ...

  9. java后台发送https请求(基于httpTemplate的httpUtil工具实现)

    最近做连续做了一些java后台发送http请求的需求,发现项目里实现http请求的写法各异,不够简洁统一,于是基于httpTemplate自行封装了一个http请求工具,常见的json和octet-s ...

最新文章

  1. Win7下U盘安装Ubuntu14.04双系统
  2. 突破NP屏蔽,实现按键模拟!
  3. 百度语音识别技术负责人李先刚:如何利用Deep CNN大幅提升识别准确率?
  4. matlab四维图程序,Matlab 四维图形绘制
  5. Qt学习之路(11): MainWindow
  6. BZOJ1876 [SDOI2009]SuperGCD 【高精 + GCD优化】
  7. linux qt yuv,c – 如何使用Qt中的RGBA32数据将带有YUV数据...
  8. 求职者:推销自己的四大妙招
  9. C#_asp.net mvc 验证码功能的具体实现
  10. 2008年全国计算机软考程序员考试大纲
  11. 怎么解决mysql登录闪退问题
  12. android 版本更新 静默安装及自启动
  13. 多语言国际版在线聊天室/匿名在线聊天室/语音聊天室/网页APP聊天室
  14. 如何实现一个去中心化的 Dropbox 存储
  15. 开封文化艺术职业学院计算机甲骨文,甲骨文软件学院致19级全体同学的一封信 暨2021年寒假作业安排...
  16. 【未解决】CMD窗口无法显示带颜色文字输出
  17. 英文文本大小写的转换
  18. 构建AWS Site-to-Site IPsec实现内网互联
  19. windows 远程连接
  20. 对一阶二阶低通数字滤波器的理解

热门文章

  1. 基于SOCK_RAW的泛洪攻击
  2. matlab统计文本数据画直方图,matlab从txt中读取某列数据画直方图
  3. SharePoint Designer (FrontPage) 2007 简体中文正式版
  4. html ajax 图片上传,Ajax实现图片上传并预览功能
  5. 求两个数的最大公约数(互质算法)
  6. STM32 HAL 驱动有刷直流电机和无刷直流电机
  7. 获取本机的真实IP地址
  8. 列举一些 MacBook Pro 必需的外设和应用程序推荐
  9. 今天,我要挺一把 CSDN!
  10. Excel技巧:怎么比较两列文本