zoukankan      html  css  js  c++  java
  • Android进阶——Volley+Https给你的安卓应用加上SSL证书(转)

    背景 

         作为开发人员,我们需要对网络访问的安全性加以保证,这样才能在基本上保证我们的数据不受到修改和攻击。笔者的项目之前用的是Volley框架访问的网络,基于http协议。现在我们需要使用更为安全的https。https简单的理解就是http+ssl,对于SSL证书,自己签发也行,花钱购买也可以,孰优孰劣,大家自行百度了解。
         因为是基于Volley框架访问的网络,所以网上搜到的许多方法都不能用了,经过大量筛选测试,最靠谱的方法就是修改Volley源码了。

    PASS

         刚开始想着下载个Volley的jar包,修改完毕再直接生成新的jar来使用,可是生成新jar后的签名和源jar包不一致,所以无法使用了。此方案PASS。

    改源码

         后来直接下载Volley的zip包,(点击下载,侵删)。先把它运行起来,(该Volley项目是用Android Studio写的),如果你的项目同样是Studio写的,那就比较省事了。笔者目前还用的是老旧的Eclipse,直接导入就行,差别也不太大。找到android.volley.toolbox下面的Volley.java文件,对里面的内容进行修改替换。替换后的代码如下:

    Volley.java代码

    [java] view plain copy
     
    1. /* 
    2.  * Copyright (C) 2012 The Android Open Source Project 
    3.  * 
    4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
    5.  * you may not use this file except in compliance with the License. 
    6.  * You may obtain a copy of the License at 
    7.  * 
    8.  *      http://www.apache.org/licenses/LICENSE-2.0 
    9.  * 
    10.  * Unless required by applicable law or agreed to in writing, software 
    11.  * distributed under the License is distributed on an "AS IS" BASIS, 
    12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
    13.  * See the License for the specific language governing permissions and 
    14.  * limitations under the License. 
    15.  */  
    16.   
    17. package com.android.volley.toolbox;  
    18.   
    19. import java.io.File;  
    20. import java.io.IOException;  
    21. import java.io.InputStream;  
    22. import java.security.KeyManagementException;  
    23. import java.security.KeyStore;  
    24. import java.security.KeyStoreException;  
    25. import java.security.NoSuchAlgorithmException;  
    26. import java.security.UnrecoverableKeyException;  
    27. import java.security.cert.Certificate;  
    28. import java.security.cert.CertificateException;  
    29. import java.security.cert.CertificateFactory;  
    30.   
    31. import javax.net.ssl.SSLContext;  
    32. import javax.net.ssl.SSLSocketFactory;  
    33. import javax.net.ssl.TrustManagerFactory;  
    34.   
    35. import org.apache.http.client.HttpClient;  
    36. import org.apache.http.conn.scheme.PlainSocketFactory;  
    37. import org.apache.http.conn.scheme.Scheme;  
    38. import org.apache.http.conn.scheme.SchemeRegistry;  
    39. import org.apache.http.impl.client.DefaultHttpClient;  
    40. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;  
    41. import org.apache.http.params.BasicHttpParams;  
    42. import org.apache.http.params.HttpParams;  
    43.   
    44. import android.content.Context;  
    45. import android.content.pm.PackageInfo;  
    46. import android.content.pm.PackageManager.NameNotFoundException;  
    47. import android.net.http.AndroidHttpClient;  
    48. import android.os.Build;  
    49.   
    50. import com.android.volley.Network;  
    51. import com.android.volley.RequestQueue;  
    52. import com.jiemi.waiter.R;  
    53.   
    54. public class Volley {  
    55.   
    56.     /** 
    57.      * Default on-disk cache directory. 
    58.      */  
    59.     private static final String DEFAULT_CACHE_DIR = "volley";  
    60.   
    61.     private Context mContext;  
    62.   
    63.     /** 
    64.      * Creates a default instance of the worker pool and calls 
    65.      * {@link RequestQueue#start()} on it. 
    66.      *  
    67.      * @param context 
    68.      *            A {@link Context} to use for creating the cache dir. 
    69.      * @param stack 
    70.      *            An {@link HttpStack} to use for the network, or null for 
    71.      *            default. 
    72.      * @return A started {@link RequestQueue} instance. 
    73.      */  
    74.     public static RequestQueue newRequestQueue(Context context,  
    75.             HttpStack stack, boolean selfSignedCertificate, int rawId) {  
    76.         File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);  
    77.   
    78.         String userAgent = "volley/0";  
    79.         try {  
    80.             String packageName = context.getPackageName();  
    81.             PackageInfo info = context.getPackageManager().getPackageInfo(  
    82.                     packageName, 0);  
    83.             userAgent = packageName + "/" + info.versionCode;  
    84.         } catch (NameNotFoundException e) {  
    85.         }  
    86.   
    87.         if (stack == null) {  
    88.             if (Build.VERSION.SDK_INT >= 9) {  
    89.                 if (selfSignedCertificate) {  
    90.                     stack = new HurlStack(null, buildSSLSocketFactory(context,  
    91.                             rawId));  
    92.                 } else {  
    93.                     stack = new HurlStack();  
    94.                 }  
    95.             } else {  
    96.                 // Prior to Gingerbread, HttpUrlConnection was unreliable.  
    97.                 // See:  
    98.                 // http://android-developers.blogspot.com/2011/09/androids-http-clients.html  
    99.                 if (selfSignedCertificate)  
    100.                     stack = new HttpClientStack(getHttpClient(context, rawId));  
    101.                 else {  
    102.                     stack = new HttpClientStack(  
    103.                             AndroidHttpClient.newInstance(userAgent));  
    104.                 }  
    105.             }  
    106.         }  
    107.   
    108.         Network network = new BasicNetwork(stack);  
    109.   
    110.         RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir),  
    111.                 network);  
    112.         queue.start();  
    113.   
    114.         return queue;  
    115.     }  
    116.   
    117.     /** 
    118.      * Creates a default instance of the worker pool and calls 
    119.      * {@link RequestQueue#start()} on it. 
    120.      *  
    121.      * @param context 
    122.      *            A {@link Context} to use for creating the cache dir. 
    123.      * @return A started {@link RequestQueue} instance. 
    124.      */  
    125.     public static RequestQueue newRequestQueue(Context context) {  
    126.         // 如果你目前还没有证书,那么先用下面的这行代码,http可以照常使用.  
    127.         // return newRequestQueue(context, null, false, 0);  
    128.         // 此处R.raw.certificateName 表示你的证书文件,替换为自己证书文件名字就好  
    129.         return newRequestQueue(context, null, true, R.raw.certificateName);  
    130.     }  
    131.   
    132.     private static SSLSocketFactory buildSSLSocketFactory(Context context,  
    133.             int certRawResId) {  
    134.         KeyStore keyStore = null;  
    135.         try {  
    136.             keyStore = buildKeyStore(context, certRawResId);  
    137.         } catch (KeyStoreException e) {  
    138.             e.printStackTrace();  
    139.         } catch (CertificateException e) {  
    140.             e.printStackTrace();  
    141.         } catch (NoSuchAlgorithmException e) {  
    142.             e.printStackTrace();  
    143.         } catch (IOException e) {  
    144.             e.printStackTrace();  
    145.         }  
    146.   
    147.         String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();  
    148.         TrustManagerFactory tmf = null;  
    149.         try {  
    150.             tmf = TrustManagerFactory.getInstance(tmfAlgorithm);  
    151.             tmf.init(keyStore);  
    152.   
    153.         } catch (NoSuchAlgorithmException e) {  
    154.             e.printStackTrace();  
    155.         } catch (KeyStoreException e) {  
    156.             e.printStackTrace();  
    157.         }  
    158.   
    159.         SSLContext sslContext = null;  
    160.         try {  
    161.             sslContext = SSLContext.getInstance("TLS");  
    162.         } catch (NoSuchAlgorithmException e) {  
    163.             e.printStackTrace();  
    164.         }  
    165.         try {  
    166.             sslContext.init(null, tmf.getTrustManagers(), null);  
    167.         } catch (KeyManagementException e) {  
    168.             e.printStackTrace();  
    169.         }  
    170.   
    171.         return sslContext.getSocketFactory();  
    172.   
    173.     }  
    174.   
    175.     private static HttpClient getHttpClient(Context context, int certRawResId) {  
    176.         KeyStore keyStore = null;  
    177.         try {  
    178.             keyStore = buildKeyStore(context, certRawResId);  
    179.         } catch (KeyStoreException e) {  
    180.             e.printStackTrace();  
    181.         } catch (CertificateException e) {  
    182.             e.printStackTrace();  
    183.         } catch (NoSuchAlgorithmException e) {  
    184.             e.printStackTrace();  
    185.         } catch (IOException e) {  
    186.             e.printStackTrace();  
    187.         }  
    188.         if (keyStore != null) {  
    189.         }  
    190.         org.apache.http.conn.ssl.SSLSocketFactory sslSocketFactory = null;  
    191.         try {  
    192.             sslSocketFactory = new org.apache.http.conn.ssl.SSLSocketFactory(  
    193.                     keyStore);  
    194.         } catch (NoSuchAlgorithmException e) {  
    195.             e.printStackTrace();  
    196.         } catch (KeyManagementException e) {  
    197.             e.printStackTrace();  
    198.         } catch (KeyStoreException e) {  
    199.             e.printStackTrace();  
    200.         } catch (UnrecoverableKeyException e) {  
    201.             e.printStackTrace();  
    202.         }  
    203.   
    204.         HttpParams params = new BasicHttpParams();  
    205.   
    206.         SchemeRegistry schemeRegistry = new SchemeRegistry();  
    207.         schemeRegistry.register(new Scheme("http", PlainSocketFactory  
    208.                 .getSocketFactory(), 80));  
    209.         schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));  
    210.   
    211.         ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(  
    212.                 params, schemeRegistry);  
    213.   
    214.         return new DefaultHttpClient(cm, params);  
    215.     }  
    216.   
    217.     private static KeyStore buildKeyStore(Context context, int certRawResId)  
    218.             throws KeyStoreException, CertificateException,  
    219.             NoSuchAlgorithmException, IOException {  
    220.         String keyStoreType = KeyStore.getDefaultType();  
    221.         KeyStore keyStore = KeyStore.getInstance(keyStoreType);  
    222.         keyStore.load(null, null);  
    223.   
    224.         Certificate cert = readCert(context, certRawResId);  
    225.         keyStore.setCertificateEntry("ca", cert);  
    226.   
    227.         return keyStore;  
    228.     }  
    229.   
    230.     private static Certificate readCert(Context context, int certResourceID) {  
    231.         InputStream inputStream = context.getResources().openRawResource(  
    232.                 certResourceID);  
    233.         Certificate ca = null;  
    234.   
    235.         CertificateFactory cf = null;  
    236.         try {  
    237.             cf = CertificateFactory.getInstance("X.509");  
    238.             ca = cf.generateCertificate(inputStream);  
    239.   
    240.         } catch (CertificateException e) {  
    241.             e.printStackTrace();  
    242.         }  
    243.         return ca;  
    244.     }  
    245. }  

    改自己的项目

         然后就是大刀阔斧的改自己的项目了。首先把证书文件拷贝到res/raw文件夹下。然后把libs下面的Volley.jar包删除,会发现多处报错(把访问网络的代码删除了当然会报错),先不用管,接着把自己刚才修改的Volley源码添加过来。直接把com.android.volley直接copy到自己项目的src下,把上面源码中提到的证书文件的名字替换为自己项目证书的名字就可以了。

    小结

         起初也是一头雾水,查了好多文章,咨询了许多朋友,总算是顺利的用上了https。所以呢,世上本没有路,尝试的多了,也会踏出一条路。Go on !

    转 http://blog.csdn.net/haovip123/article/details/49509045

  • 相关阅读:
    创建共享内存函数CreateFileMapping()详解
    窗口类、窗口类对象与窗口
    ubuntu中文版切换为英文后字体变化问题解决
    安装ubuntu12.04LTS卡住以及花屏问题
    时钟周期、振荡周期、机器周期、CPU周期、状态周期、指令周期、总线周期、任务周期
    波特率
    myod
    mycp
    20165226 2017-2018-2《Java程序设计》课程总结
    2017-2018-2 20165226 实验五《网络编程与安全》实验报告
  • 原文地址:https://www.cnblogs.com/taoboy/p/5254133.html
Copyright © 2011-2022 走看看