UDN-企业互联网技术人气社区

板块导航

浏览  : 1093
回复  : 0

[干货] Android的使用HTTPS

[复制链接]
开花包的头像 楼主
发表于 2017-1-1 22:07:39 | 显示全部楼层 |阅读模式
  如果你的项目的网络框架是okhttp,那么使用HTTPS还是挺简单的,因为okhttp默认支持HTTPS。传送门

  Android的使用HTTPS配置的步骤。

  步

  配置的HostnameVerifier

  1.   new HostnameVerifier() {

  2.   @Override

  3.   public boolean verify(String hostname, SSLSession session) {

  4.   return true;

  5.   }

  6.   };
复制代码


  2.step

  配置的SSLSocketFactory

  1.   public static SSLSocketFactory getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password){

  2.   try{

  3.   TrustManager[] trustManagers = prepareTrustManager(certificates);

  4.   KeyManager[] keyManagers = prepareKeyManager(bksFile, password);

  5.   SSLContext sslContext = SSLContext.getInstance("TLS");

  6.   TrustManager trustManager = null;

  7.   if (trustManagers != null){

  8.   trustManager = new MyTrustManager(chooseTrustManager(trustManagers));

  9.   } else{

  10.   trustManager = new UnSafeTrustManager();

  11.   }

  12.   sslContext.init(keyManagers, new TrustManager[]{trustManager}, new SecureRandom());

  13.   return sslContext.getSocketFactory();

  14.   } catch (NoSuchAlgorithmException e){

  15.   throw new AssertionError(e);

  16.   } catch (KeyManagementException e){

  17.   throw new AssertionError(e);

  18.   } catch (KeyStoreException e){

  19.   throw new AssertionError(e);

  20.   }

  21.   }

  22.   private class UnSafeHostnameVerifier implements HostnameVerifier{

  23.   @Override

  24.   public boolean verify(String hostname, SSLSession session){

  25.   return true;

  26.   }

  27.   }

  28.   private static class UnSafeTrustManager implements X509TrustManager{

  29.   @Override

  30.   public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException{}

  31.   @Override

  32.   public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException{}

  33.   @Override

  34.   public X509Certificate[] getAcceptedIssuers(){

  35.   return new X509Certificate[]{};

  36.   }

  37.   }

  38.   private static TrustManager[] prepareTrustManager(InputStream... certificates){

  39.   if (certificates == null || certificates.length <= 0) return null;

  40.   try{

  41.   CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

  42.   KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

  43.   keyStore.load(null);

  44.   int index = 0;

  45.   for (InputStream certificate : certificates){

  46.   String certificateAlias = Integer.toString(index++);

  47.   keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));

  48.   try{

  49.   if (certificate != null)

  50.   certificate.close();

  51.   } catch (IOException e){

  52.   }

  53.   }

  54.   TrustManagerFactory trustManagerFactory = null;

  55.   trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

  56.   trustManagerFactory.init(keyStore);

  57.   TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

  58.   return trustManagers;

  59.   } catch (NoSuchAlgorithmException e){

  60.   e.printStackTrace();

  61.   } catch (CertificateException e){

  62.   e.printStackTrace();

  63.   } catch (KeyStoreException e){

  64.   e.printStackTrace();

  65.   } catch (Exception e){

  66.   e.printStackTrace();

  67.   }

  68.   return null;

  69.   }

  70.   private static KeyManager[] prepareKeyManager(InputStream bksFile, String password){

  71.   try{

  72.   if (bksFile == null || password == null) return null;

  73.   KeyStore clientKeyStore = KeyStore.getInstance("BKS");

  74.   clientKeyStore.load(bksFile, password.toCharArray());

  75.   KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

  76.   keyManagerFactory.init(clientKeyStore, password.toCharArray());

  77.   return keyManagerFactory.getKeyManagers();

  78.   } catch (KeyStoreException e){

  79.   e.printStackTrace();

  80.   } catch (NoSuchAlgorithmException e){

  81.   e.printStackTrace();

  82.   } catch (UnrecoverableKeyException e){

  83.   e.printStackTrace();

  84.   } catch (CertificateException e){

  85.   e.printStackTrace();

  86.   } catch (IOException e){

  87.   e.printStackTrace();

  88.   } catch (Exception e){

  89.   e.printStackTrace();

  90.   }

  91.   return null;

  92.   }

  93.   private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers){

  94.   for (TrustManager trustManager : trustManagers){

  95.   if (trustManager instanceof X509TrustManager){

  96.   return (X509TrustManager) trustManager;

  97.   }

  98.   }

  99.   return null;

  100.   }

  101.   private static class MyTrustManager implements X509TrustManager{

  102.   private X509TrustManager defaultTrustManager;

  103.   private X509TrustManager localTrustManager;

  104.   public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException{

  105.   TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

  106.   var4.init((KeyStore) null);

  107.   defaultTrustManager = chooseTrustManager(var4.getTrustManagers());

  108.   this.localTrustManager = localTrustManager;

  109.   }

  110.   @Override

  111.   public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException{}

  112.   @Override

  113.   public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException{

  114.   try{

  115.   defaultTrustManager.checkServerTrusted(chain, authType);

  116.   } catch (CertificateException ce){

  117.   localTrustManager.checkServerTrusted(chain, authType);

  118.   }

  119.   }

  120.   @Override

  121.   public X509Certificate[] getAcceptedIssuers(){

  122.   return new X509Certificate[0];

  123.   }

  124.   }
复制代码


  调用getSslSocketFactory(NULL,NULL,NULL)即可。

  3.step

  设置OkhttpClient。

1.png


  方法getSslSocketFactory(NULL,NULL,NULL)的第一个参数本来要传入自签名证书的,当传入空即可忽略自签名证书。

  如果你想尝试不忽略自签名证书你可以调用下面的方法获取的SSLSocketFactory。并设置到OkhttpClient中。

  1.   public static SSLSocketFactory getSSlFactory(Context context) {

  2.   try {

  3.   CertificateFactory cf = CertificateFactory.getInstance("X.509");

  4.   InputStream caInput = new BufferedInputStream(context.getAssets().open("client.cer"));//把证书打包在asset文件夹中

  5.   Certificate ca;

  6.   try {

  7.   ca = cf.generateCertificate(caInput);

  8.   LogUtil.d("Longer", "ca=" + ((X509Certificate) ca).getSubjectDN());

  9.   LogUtil.d("Longer", "key=" + ((X509Certificate) ca).getPublicKey());

  10.   } finally {

  11.   caInput.close();

  12.   }

  13.   // Create a KeyStore containing our trusted CAs

  14.   String keyStoreType = KeyStore.getDefaultType();

  15.   KeyStore keyStore = KeyStore.getInstance(keyStoreType);

  16.   keyStore.load(null, null);

  17.   keyStore.setCertificateEntry("ca", ca);

  18.   // Create a TrustManager that trusts the CAs in our KeyStore

  19.   String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();

  20.   TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);

  21.   tmf.init(keyStore);

  22.   // Create an SSLContext that uses our TrustManager

  23.   SSLContext s = SSLContext.getInstance("TLSv1", "AndroidOpenSSL");

  24.   s.init(null, tmf.getTrustManagers(), null);

  25.   return s.getSocketFactory();

  26.   } catch (CertificateException e) {

  27.   e.printStackTrace();

  28.   } catch (IOException e) {

  29.   e.printStackTrace();

  30.   } catch (NoSuchAlgorithmException e) {

  31.   e.printStackTrace();

  32.   } catch (KeyStoreException e) {

  33.   e.printStackTrace();

  34.   } catch (KeyManagementException e) {

  35.   e.printStackTrace();

  36.   } catch (NoSuchProviderException e) {

  37.   e.printStackTrace();

  38.   }

  39.   return null;

  40.   }
复制代码


  通过上面的几步配置即可使用HTTPS的自签名证书和单向验证的的Https了。

  滑翔访问的Https的图片

  1.step

  在的build.gradle引入下面的AAR

  / 提供的模块 /

  编译“com.github.bumptech.glide:okhttp3集成:1.4.0@aar”

  2.step

  1.   OkHttpClient okhttpClient = new OkHttpClient.Builder()

  2.   .connectTimeout(30, TimeUnit.SECONDS)

  3.   .retryOnConnectionFailure(true) //设置出现错误进行重新连接。

  4.   .connectTimeout(15, TimeUnit.SECONDS)

  5.   .readTimeout(60 * 1000, TimeUnit.MILLISECONDS)

  6.   .sslSocketFactory(HttpsUtils.getSslSocketFactory(null,null,null))

  7.   .hostnameVerifier(new HostnameVerifier() {

  8.   @Override

  9.   public boolean verify(String hostname, SSLSession session) {

  10.   return true;

  11.   }

  12.   })

  13.   .build();

  14.   //让Glide能用HTTPS

  15.   Glide.get(this).register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okhttpClient));
复制代码


  设置已经验证证书的的OkhttpClient到滑翔既可。

  结束。

原文作者:maimingliang 来源:开发者头条

相关帖子

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关于我们
联系我们
  • 电话:010-86393388
  • 邮件:udn@yonyou.com
  • 地址:北京市海淀区北清路68号
移动客户端下载
关注我们
  • 微信公众号:yonyouudn
  • 扫描右侧二维码关注我们
  • 专注企业互联网的技术社区
版权所有:用友网络科技股份有限公司82041 京ICP备05007539号-11 京公网网备安1101080209224 Powered by Discuz!
快速回复 返回列表 返回顶部