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”,而得不到数据。


相关文章
|
12月前
|
算法 数据库 数据安全/隐私保护
摘要认证,使用HttpClient实现HTTP digest authentication
这篇文章提供了使用HttpClient实现HTTP摘要认证(digest authentication)的详细步骤和示例代码。
842 2
|
11月前
|
存储 XML 自然语言处理
信息检索和信息提取的区别 原文出自[易百教程] 转载请保留原文链接: https://www.yiibai.com/geek/331046
提取的意思是 “取出”,检索的意思是 “取回”。信息检索是返回与用户特定查询或兴趣领域相关的信息。而信息提取则更多地是从一组文档或信息中提取一般知识(或关系)。信息提取是获取数据并从中提取结构化信息的标准过程,以便将其用于各种目的,其中一个目的可能是搜索引擎。
317 24
|
12月前
|
Java Unix Linux
Android Studio中Terminal运行./gradlew clean build提示错误信息
遇到 `./gradlew clean build`命令执行出错时,首先应检查错误信息的具体内容,这通常会指向问题的根源。从权限、环境配置、依赖下载、版本兼容性到项目配置本身,逐一排查并应用相应的解决措施。记住,保持耐心,逐步解决问题,往往复杂问题都是由简单原因引起的。
1016 2
|
存储 网络安全 数据安全/隐私保护
[flask]使用mTLS双向加密认证http通信
【7月更文挑战第16天】在Flask应用中实现mTLS双向TLS加密认证可增强HTTP通信安全性。步骤包括: 1. 使用OpenSSL为服务器和客户端生成证书和密钥。 2. 配置Flask服务器使用这些证书: - 安装`flask`和`pyopenssl`. - 设置SSL上下文并启用mTLS验证: 注意事项: - 保持证书有效期并及时更新. - 确保证书链信任. - 充分测试mTLS配置.
274 2
Qt http的认证方式以及简单实现
以上就是Qt实现HTTP认证的基本步骤。需要注意的是,以上代码未进行错误处理,实际使用时需要根据具体情况进行相应的错误处理。
260 1
|
安全 网络安全 数据安全/隐私保护
[flask]使用mTLS双向加密认证http通信
[flask]使用mTLS双向加密认证http通信
280 0
|
网络协议 应用服务中间件 Go
[golang]使用mTLS双向加密认证http通信
[golang]使用mTLS双向加密认证http通信
265 0
|
存储 Android开发
详细解读Android获取已安装应用信息(图标,名称,版本号,包)
详细解读Android获取已安装应用信息(图标,名称,版本号,包)
460 0
vue : 无法加载文件 D:\module\npm_module\npm_modules\vue.ps1,因为在此系统上禁止运行脚本。有关详细信息,请参阅 https:/go.microsoft.c
vue : 无法加载文件 D:\module\npm_module\npm_modules\vue.ps1,因为在此系统上禁止运行脚本。有关详细信息,请参阅 https:/go.microsoft.c
|
Shell 开发工具 Android开发
android 修改kernel编译版本信息
android 修改kernel编译版本信息
152 0