Android HTTPS验证和添加http头信息token认证

本文涉及的产品
Digicert DV 证书 单域名,20个 3个月
简介:


 实现https信任所有证书的方法

Android平台上经常有使用https的需求,对于https服务器使用的根证书是受信任的证书的话,实现https是非常简单的,直接用httpclient库就行了,与使用http几乎没有区别。但是在大多数情况下,服务器所使用的根证书是自签名的,或者签名机构不在设备的信任证书列表中,这样使用httpclient进行https连接就会失败。解决这个问题的办法有两种,一是在发起https连接之前将服务器证书加到httpclient的信任证书列表中,这个相对来说比较复杂一些,很容易出错;另一种办法是让httpclient信任所有的服务器证书,这种办法相对来说简单很多,但安全性则差一些,但在某些场合下有一定的应用场景。这里要举例说明的就是后一种方法:实例化HttpClinet对象时要进行一些处理主要是绑定https连接所使用的端口号,这里绑定了443和8443:

[java]  view plain copy
  1. SchemeRegistry schemeRegistry = new SchemeRegistry();  
  2. schemeRegistry.register(new Scheme("https",  
  3.                     new EasySSLSocketFactory(), 443));  
  4. schemeRegistry.register(new Scheme("https",  
  5.                     new EasySSLSocketFactory(), 8443));  
  6. ClientConnectionManager connManager = new ThreadSafeClientConnManager(params, schemeRegistry);  
  7. HttpClient httpClient = new DefaultHttpClient(connManager, params);  


上面的EasySSLSocketFactory类是我们自定义的,主要目的就是让httpclient接受所有的服务器证书,能够正常的进行https数据读取。相关代码如下:

[java]  view plain copy
  1. public class EasySSLSocketFactory implements SocketFactory,  
  2.         LayeredSocketFactory {  
  3.   
  4.     private SSLContext sslcontext = null;  
  5.   
  6.     private static SSLContext createEasySSLContext() throws IOException {  
  7.         try {  
  8.             SSLContext context = SSLContext.getInstance("TLS");  
  9.             context.init(nullnew TrustManager[] { new EasyX509TrustManager(  
  10.                     null) }, null);  
  11.             return context;  
  12.         } catch (Exception e) {  
  13.             throw new IOException(e.getMessage());  
  14.         }  
  15.     }  
  16.   
  17.     private SSLContext getSSLContext() throws IOException {  
  18.         if (this.sslcontext == null) {  
  19.             this.sslcontext = createEasySSLContext();  
  20.         }  
  21.         return this.sslcontext;  
  22.     }  
  23.   
  24.      
  25.     public Socket connectSocket(Socket sock, String host, int port,  
  26.             InetAddress localAddress, int localPort, HttpParams params)  
  27.             throws IOException, UnknownHostException, ConnectTimeoutException {  
  28.         int connTimeout = HttpConnectionParams.getConnectionTimeout(params);  
  29.         int soTimeout = HttpConnectionParams.getSoTimeout(params);  
  30.   
  31.         InetSocketAddress remoteAddress = new InetSocketAddress(host, port);  
  32.         SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());  
  33.   
  34.         if ((localAddress != null) || (localPort > 0)) {  
  35.             // we need to bind explicitly  
  36.             if (localPort < 0) {  
  37.                 localPort = 0// indicates "any"  
  38.             }  
  39.             InetSocketAddress isa = new InetSocketAddress(localAddress,  
  40.                     localPort);  
  41.             sslsock.bind(isa);  
  42.         }  
  43.   
  44.         sslsock.connect(remoteAddress, connTimeout);  
  45.         sslsock.setSoTimeout(soTimeout);  
  46.         return sslsock;  
  47.   
  48.     }  
  49.   
  50.      
  51.     public Socket createSocket() throws IOException {  
  52.         return getSSLContext().getSocketFactory().createSocket();  
  53.     }  
  54.   
  55.      
  56.     public boolean isSecure(Socket socket) throws IllegalArgumentException {  
  57.         return true;  
  58.     }  
  59.   
  60.      
  61.     public Socket createSocket(Socket socket, String host, int port,  
  62.             boolean autoClose) throws IOException, UnknownHostException {  
  63.         return getSSLContext().getSocketFactory().createSocket(socket, host,  
  64.                 port, autoClose);  
  65.     }  
  66.   
  67.     // -------------------------------------------------------------------  
  68.     // javadoc in org.apache.http.conn.scheme.SocketFactory says :  
  69.     // Both Object.equals() and Object.hashCode() must be overridden  
  70.     // for the correct operation of some connection managers  
  71.     // -------------------------------------------------------------------  
  72.   
  73.     public boolean equals(Object obj) {  
  74.         return ((obj != null) && obj.getClass().equals(  
  75.                 EasySSLSocketFactory.class));  
  76.     }  
  77.   
  78.     public int hashCode() {  
  79.         return EasySSLSocketFactory.class.hashCode();  
  80.     }  
  81. }  
  82.   
  83. public class EasyX509TrustManager implements X509TrustManager {  
  84.   
  85.     private X509TrustManager standardTrustManager = null;  
  86.   
  87.      
  88.     public EasyX509TrustManager(KeyStore keystore)  
  89.             throws NoSuchAlgorithmException, KeyStoreException {  
  90.         super();  
  91.         TrustManagerFactory factory = TrustManagerFactory  
  92.                .getInstance(TrustManagerFactory.getDefaultAlgorithm());  
  93.         factory.init(keystore);  
  94.         TrustManager[] trustmanagers = factory.getTrustManagers();  
  95.         if (trustmanagers.length == 0) {  
  96.             throw new NoSuchAlgorithmException("no trust manager found");  
  97.         }  
  98.         this.standardTrustManager = (X509TrustManager) trustmanagers[0];  
  99.     }  
  100.   
  101.      
  102.     public void checkClientTrusted(X509Certificate[] certificates,  
  103.             String authType) throws CertificateException {  
  104.         standardTrustManager.checkClientTrusted(certificates, authType);  
  105.     }  
  106.   
  107.      
  108.     public void checkServerTrusted(X509Certificate[] certificates,  
  109.             String authType) throws CertificateException {  
  110.         if ((certificates != null) && (certificates.length == 1)) {  
  111.             certificates[0].checkValidity();  
  112.         } else {  
  113.             standardTrustManager.checkServerTrusted(certificates, authType);  
  114.         }  
  115.     }  
  116.   
  117.      
  118.     public X509Certificate[] getAcceptedIssuers() {  
  119.         return this.standardTrustManager.getAcceptedIssuers();  
  120.     }  
  121. }  


[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. SchemeRegistry schemeRegistry = new SchemeRegistry();  
  2.         schemeRegistry.register(new Scheme("http", PlainSocketFactory  
  3.                 .getSocketFactory(), 80));  
  4.   
  5.         SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();  
  6.         try {  
  7.             KeyStore trustStore = KeyStore.getInstance(KeyStore  
  8.                     .getDefaultType());  
  9.             trustStore.load(nullnull);  
  10.             sf = new SSLSocketFactoryEx(trustStore);  
  11.             sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  12.             // 允许所有主机的验证  
  13.         } catch (Exception e) {  
  14.             Log.e("erro""SSLSocketFactory Error");  
  15.         }  
  16.   
  17.         schemeRegistry.register(new Scheme("https", sf, 443));  
  18.         ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(  
  19.                 httpParams, schemeRegistry);  
  20. DefaultHttpClient httpClient = new DefaultHttpClient(cm, httpParams);  


上面的 SSLSocketFactoryEx 类主要目的就是让httpclient接受所有的服务器证书,能够正常的进行https数据读取。相关代码如下:

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. class SSLSocketFactoryEx extends SSLSocketFactory {  
  2.   
  3.         SSLContext sslContext = SSLContext.getInstance("TLS");  
  4.   
  5.         public SSLSocketFactoryEx(KeyStore truststore)  
  6.                 throws NoSuchAlgorithmException, KeyManagementException,  
  7.                 KeyStoreException, UnrecoverableKeyException {  
  8.             super(truststore);  
  9.   
  10.             TrustManager tm = new X509TrustManager() {  
  11.   
  12.                 @Override  
  13.                 public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
  14.                     return null;  
  15.                 }  
  16.   
  17.                 @Override  
  18.                 public void checkClientTrusted(  
  19.                         java.security.cert.X509Certificate[] chain,  
  20.                         String authType)  
  21.                         throws java.security.cert.CertificateException {  
  22.   
  23.                 }  
  24.   
  25.                 @Override  
  26.                 public void checkServerTrusted(  
  27.                         java.security.cert.X509Certificate[] chain,  
  28.                         String authType)  
  29.                         throws java.security.cert.CertificateException {  
  30.   
  31.                 }  
  32.             };  
  33.   
  34.             sslContext.init(nullnew TrustManager[] { tm }, null);  
  35.         }  
  36.   
  37.         @Override  
  38.         public Socket createSocket(Socket socket, String host, int port,  
  39.                 boolean autoClose) throws IOException, UnknownHostException {  
  40.             return sslContext.getSocketFactory().createSocket(socket, host,  
  41.                     port, autoClose);  
  42.         }  
  43.   
  44.         @Override  
  45.         public Socket createSocket() throws IOException {  
  46.             return sslContext.getSocketFactory().createSocket();  
  47.         }  
  48.     }  

添加http头信息token认证

有时候服务器端需要传递token来验证请求来源是否是受信任的,以增强安全性:

httppost.addHeader("Authorization", "your token"); //token认证
重点是有些服务器要求将token转化成Base64编码。

于是  String token ="Basic " + Base64.encodeToString("your token".getBytes(), Base64.NO_WRAP);

注意,参数是 Base64.NO_WRAP而不是Base64.DEFAULT 。而否则会返回 “400 Bad Request”,而得不到数据。


相关实践学习
通过HTTPS加速网关快速部署网站加密
本实验指导您如何在HTTPS加速网关中添加域名,以及在添加域名后如何进行修改和重置。
相关文章
|
4天前
|
存储 数据采集 运维
DataWorks产品使用合集之DataWorks创建HTTP触发器节点背景信息的步骤如何解决
DataWorks作为一站式的数据开发与治理平台,提供了从数据采集、清洗、开发、调度、服务化、质量监控到安全管理的全套解决方案,帮助企业构建高效、规范、安全的大数据处理体系。以下是对DataWorks产品使用合集的概述,涵盖数据处理的各个环节。
15 0
|
5天前
|
安全 网络协议 算法
【计算机网络】http协议的原理与应用,https是如何保证安全传输的
【计算机网络】http协议的原理与应用,https是如何保证安全传输的
|
5天前
|
网络协议 安全 算法
HTTP协议与HTTPS协议
HTTP协议与HTTPS协议
|
6天前
|
数据采集 缓存 网络协议
静态代理IP是否支持HTTP和HTTPS?
静态代理IP支持HTTP、HTTPS、FTP、Socks5等协议,HTTP协议因其简单、灵活而常用,通常比HTTPS速度快,因无需加密处理。HTTP代理比SOCKS5代理通常更快,因为HTTP专注于HTTP请求,而SOCKS5处理多种网络流量。静态HTTP代理适合浏览器和爬虫,SOCKS5代理支持更多协议,如TCP、UDP。选择取决于应用场景和需求。
|
10天前
|
安全 Go
解决https页面加载http资源报错
请注意,混合内容可能导致安全性问题,因此在使用上述方法时要小心。最好的方式是尽量减少或完全消除混合内容,以确保页面的安全性。
8 0
|
15天前
|
网络协议 网络安全 数据安全/隐私保护
http和https的区别!
http和https的区别!
|
17天前
|
安全 网络协议 前端开发
< 了解 HTTP 这一篇就够了 :什么是 HTTP ?HTTP 和 HTTPS 有什么区别 ? >
在前端开发中,是和浏览器打交道最为频繁的行业之一。但是大部分卷王们,可能仅仅是知道如何使用浏览器,只是知道 URL 跳转到浏览器变成一个完整的网页。 本篇文章将讲述 什么是HTTP、 HTTP 和 HTTPS的区别 及 URL 是如何渲染到页面。 那么到这里,肯定会有人问: 那我们为什么要学习这个呢 ? 问得好,这个分为两方面: 一是学习上述内容,能够厚实我们的理论基础。有些内容,虽然用的不多,但是技多不压身,道理懂吧? 二是学习这个,对我们后续的性能优化、排查浏览器上某些错误 的能力都有提升!
< 了解 HTTP 这一篇就够了 :什么是 HTTP ?HTTP 和 HTTPS 有什么区别 ? >
|
18天前
|
网络协议 安全 API
Android网络和数据交互: 什么是HTTP和HTTPS?在Android中如何进行网络请求?
HTTP和HTTPS是网络数据传输协议,HTTP基于TCP/IP,简单快速,HTTPS则是加密的HTTP,确保数据安全。在Android中,过去常用HttpURLConnection和HttpClient,但HttpClient自Android 6.0起被移除。现在推荐使用支持TLS、流式上传下载、超时配置等特性的HttpsURLConnection进行网络请求。
11 0
|
21天前
|
缓存 安全 网络协议
【面试必备】HTTP和HTTPS是什么?有什么差异?
HTTP(超文本传输协议)和HTTPS(超文本传输安全协议)是用于在互联网上传输数据的协议。它们都是应用层协议,建立在TCP/IP协议栈之上,用于客户端(如浏览器)和服务器之间的通信。
23 2
|
1月前
|
存储 安全 网络协议
http和https分别是什么?
http和https分别是什么?