android https解析
程序员文章站
2022-08-09 11:31:17
https简介
https 全称 http over tls。tls是在传输层上层的协议,应用层的下层,作为一个安全层而存在,翻译过来一般叫做传输层安全协议。
对 http 而言,安全传输层是透明不...
https简介
https 全称 http over tls。tls是在传输层上层的协议,应用层的下层,作为一个安全层而存在,翻译过来一般叫做传输层安全协议。
对 http 而言,安全传输层是透明不可见的,应用层仅仅当做使用普通的 socket 一样使用 sslsocket 。
tls是基于 x.509 认证,他假定所有的数字证书都是由一个层次化的数字证书认证机构发出,即 ca。另外值得一提的是 tls 是独立于 http 的,任何应用层的协议都可以基于 tls 建立安全的传输通道,如 ssh 协议。
https工作流程
client server
1.request. 公钥(锁头)
2.client校验证书(过期时间、颁发机构)
3.生成随机数,将随机数发送给服务端
4.c/s通过随机值当key数据传输
ca要解决的问题
通过公钥使用提供的验证策略
certificatefactory certificatefactory = certificatefactory.getinstance("x.509"); inputstream cainput = new bufferedinputstream(cc.getapplication().getassets().open("aoscagsorganizationvalsha2g2r1.crt")); certificate ca=certificatefactory.generatecertificate(cainput); logger.v("fasfasf", "ca=" + ((x509certificate) ca).getsubjectdn()); logger.v("fasfasf", "key=" + ((x509certificate) ca).getpublickey()); keystore keystore = keystore.getinstance(keystore.getdefaulttype()); keystore.load(null); keystore.setcertificateentry("ca",ca); trustmanagerfactory tmf =trustmanagerfactory.getinstance(trustmanagerfactory.getdefaultalgorithm()); tmf.init(keystore);
sslcontext sslcontext = sslcontext.getinstance("tls"); sslcontext.init(null,tmf.gettrustmanagers(), new securerandom()); sslsocketfactory = sslcontext.getsocketfactory();
if (sslsocketfactory != null) { httpsurlconnection.setdefaultsslsocketfactory(sslsocketfactory); // httpsurlconnection.setdefaulthostnameverifier(new hostnameverifier() { @override public boolean verify(string hostname, sslsession session) { boolean istrustdns= configerhelper.getinstance().istrustdns(hostname); logger.v(tag, "istrustdns "+istrustdns); return istrustdns; }}); // httpsurlconnection.sethostnameverifier(new hostnameverifier() { // @override // public boolean verify(string hostname, sslsession session) { // boolean istrustdns= configerhelper.getinstance().istrustdns(hostname); // logger.v(tag, "istrustdns "+istrustdns); // return istrustdns; // } // }); }
自定义验证策略
if (sagroupsslsocketfactory == null) { try { trustmanager[] trustmanagers=new trustmanager[]{ new 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[0]; } } }; sslcontext sslcontext = sslcontext.getinstance("tls"); sslcontext.init(null,trustmanagers, new securerandom()); sslsocketfactory = sslcontext.getsocketfactory(); } catch (throwable e) { logger.v("fasfasf",""+e.getmessage()); // debuglog.error(e.getmessage(), e); } }