欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android项目中使用HTTPS配置的步骤详解

程序员文章站 2023-11-07 16:01:34
前言 如果你的项目的网络框架是okhttp,那么使用https还是挺简单的,因为okhttp默认支持https。传送门 下面话不多说了,来一起看看详细的介绍: and...

前言

如果你的项目的网络框架是okhttp,那么使用https还是挺简单的,因为okhttp默认支持https。传送门

下面话不多说了,来一起看看详细的介绍:

android 使用 https 配置的步骤。

1、step

配置hostnameverifier

 new hostnameverifier() {
   @override
    public boolean verify(string hostname, sslsession session) {
     return true;
    }
 };

2.step

配置 sslsocketfactory

public static sslsocketfactory getsslsocketfactory(inputstream[] certificates, inputstream bksfile, string password){
  try{
   trustmanager[] trustmanagers = preparetrustmanager(certificates);
   keymanager[] keymanagers = preparekeymanager(bksfile, password);
   sslcontext sslcontext = sslcontext.getinstance("tls");
   trustmanager trustmanager = null;
   if (trustmanagers != null){
    trustmanager = new mytrustmanager(choosetrustmanager(trustmanagers));
   } else{
    trustmanager = new unsafetrustmanager();
   }
   sslcontext.init(keymanagers, new trustmanager[]{trustmanager}, new securerandom());
   return sslcontext.getsocketfactory();
  } catch (nosuchalgorithmexception e){
   throw new assertionerror(e);
  } catch (keymanagementexception e){
   throw new assertionerror(e);
  } catch (keystoreexception e){
   throw new assertionerror(e);
  }
 }

 private class unsafehostnameverifier implements hostnameverifier{
  @override
  public boolean verify(string hostname, sslsession session){
   return true;
  }
 }

 private static class unsafetrustmanager implements x509trustmanager{
  @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[]{};
  }
 }

 private static trustmanager[] preparetrustmanager(inputstream... certificates){
  if (certificates == null || certificates.length <= 0) return null;
  try{
   certificatefactory certificatefactory = certificatefactory.getinstance("x.509");
   keystore keystore = keystore.getinstance(keystore.getdefaulttype());
   keystore.load(null);
   int index = 0;
   for (inputstream certificate : certificates){
    string certificatealias = integer.tostring(index++);
    keystore.setcertificateentry(certificatealias, certificatefactory.generatecertificate(certificate));
    try{
     if (certificate != null)
      certificate.close();
    } catch (ioexception e){
    }
   }
   trustmanagerfactory trustmanagerfactory = null;
   trustmanagerfactory = trustmanagerfactory.getinstance(trustmanagerfactory.getdefaultalgorithm());
   trustmanagerfactory.init(keystore);
   trustmanager[] trustmanagers = trustmanagerfactory.gettrustmanagers();
   return trustmanagers;
  } catch (nosuchalgorithmexception e){
   e.printstacktrace();
  } catch (certificateexception e){
   e.printstacktrace();
  } catch (keystoreexception e){
   e.printstacktrace();
  } catch (exception e){
   e.printstacktrace();
  }
  return null;

 }

 private static keymanager[] preparekeymanager(inputstream bksfile, string password){
  try{
   if (bksfile == null || password == null) return null;
   keystore clientkeystore = keystore.getinstance("bks");
   clientkeystore.load(bksfile, password.tochararray());
   keymanagerfactory keymanagerfactory = keymanagerfactory.getinstance(keymanagerfactory.getdefaultalgorithm());
   keymanagerfactory.init(clientkeystore, password.tochararray());
   return keymanagerfactory.getkeymanagers();
  } catch (keystoreexception e){
   e.printstacktrace();
  } catch (nosuchalgorithmexception e){
   e.printstacktrace();
  } catch (unrecoverablekeyexception e){
   e.printstacktrace();
  } catch (certificateexception e){
   e.printstacktrace();
  } catch (ioexception e){
   e.printstacktrace();
  } catch (exception e){
   e.printstacktrace();
  }
  return null;
 }

 private static x509trustmanager choosetrustmanager(trustmanager[] trustmanagers){
  for (trustmanager trustmanager : trustmanagers){
   if (trustmanager instanceof x509trustmanager){
    return (x509trustmanager) trustmanager;
   }
  }
  return null;
 }

 private static class mytrustmanager implements x509trustmanager{
  private x509trustmanager defaulttrustmanager;
  private x509trustmanager localtrustmanager;

  public mytrustmanager(x509trustmanager localtrustmanager) throws nosuchalgorithmexception, keystoreexception{
   trustmanagerfactory var4 = trustmanagerfactory.getinstance(trustmanagerfactory.getdefaultalgorithm());
   var4.init((keystore) null);
   defaulttrustmanager = choosetrustmanager(var4.gettrustmanagers());
   this.localtrustmanager = localtrustmanager;
  }

  @override
  public void checkclienttrusted(x509certificate[] chain, string authtype) throws certificateexception{}

  @override
  public void checkservertrusted(x509certificate[] chain, string authtype) throws certificateexception{
   try{
    defaulttrustmanager.checkservertrusted(chain, authtype);
   } catch (certificateexception ce){
    localtrustmanager.checkservertrusted(chain, authtype);
   }
  }

  @override
  public x509certificate[] getacceptedissuers(){
   return new x509certificate[0];
  }
 }

调用 getsslsocketfactory(null,null,null) 即可。

3.step

设置okhttpclient。

Android项目中使用HTTPS配置的步骤详解

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

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

 public static sslsocketfactory getsslfactory(context context) {

  try {
   certificatefactory cf = certificatefactory.getinstance("x.509");
   inputstream cainput = new bufferedinputstream(context.getassets().open("client.cer"));//把证书打包在asset文件夹中
   certificate ca;
   try {
    ca = cf.generatecertificate(cainput);
    logutil.d("longer", "ca=" + ((x509certificate) ca).getsubjectdn());
    logutil.d("longer", "key=" + ((x509certificate) ca).getpublickey());
   } finally {
    cainput.close();
   }

   // create a keystore containing our trusted cas
   string keystoretype = keystore.getdefaulttype();
   keystore keystore = keystore.getinstance(keystoretype);
   keystore.load(null, null);
   keystore.setcertificateentry("ca", ca);

   // create a trustmanager that trusts the cas in our keystore
   string tmfalgorithm = trustmanagerfactory.getdefaultalgorithm();
   trustmanagerfactory tmf = trustmanagerfactory.getinstance(tmfalgorithm);
   tmf.init(keystore);

   // create an sslcontext that uses our trustmanager
   sslcontext s = sslcontext.getinstance("tlsv1", "androidopenssl");
   s.init(null, tmf.gettrustmanagers(), null);

   return s.getsocketfactory();
  } catch (certificateexception e) {
   e.printstacktrace();
  } catch (ioexception e) {
   e.printstacktrace();
  } catch (nosuchalgorithmexception e) {
   e.printstacktrace();
  } catch (keystoreexception e) {
   e.printstacktrace();
  } catch (keymanagementexception e) {
   e.printstacktrace();
  } catch (nosuchproviderexception e) {
   e.printstacktrace();
  }
  return null;
 }

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

glide 访问https的图片

1.step

在build.gradle 引入下面的aar

/提供的module/
compile 'com.github.bumptech.glide:okhttp3-integration:1.4.0@aar'

2.step

 okhttpclient okhttpclient = new okhttpclient.builder()
    .connecttimeout(30, timeunit.seconds)
    .retryonconnectionfailure(true) //设置出现错误进行重新连接。
    .connecttimeout(15, timeunit.seconds)
    .readtimeout(60 * 1000, timeunit.milliseconds)
    .sslsocketfactory(httpsutils.getsslsocketfactory(null,null,null))
    .hostnameverifier(new hostnameverifier() {
     @override
     public boolean verify(string hostname, sslsession session) {
      return true;
     }
    })
     .build();
  //让glide能用https
  glide.get(this).register(glideurl.class, inputstream.class, new okhttpurlloader.factory(okhttpclient));

设置已经验证证书的的okhttpclient 到glide 既可。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。