查看: 465|回复: 0

[Android教程] Android项目中使用HTTPS配置的步骤详解

发表于 2017-11-28 08:00:01

前言

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

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

Android 使用 HTTPS 配置的步骤。

1、step

配置hostnameVerifier

  1. new HostnameVerifier() {
  2. @Override
  3. public boolean verify(String hostname, SSLSession session) {
  4. return true;
  5. }
  6. };
复制代码

2.step

配置 sslSocketFactory

  1. public static SSLSocketFactory getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password){
  2. try{
  3. TrustManager[] trustManagers = prepareTrustManager(certificates);
  4. KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
  5. SSLContext sslContext = SSLContext.getInstance("TLS");
  6. TrustManager trustManager = null;
  7. if (trustManagers != null){
  8. trustManager = new MyTrustManager(chooseTrustManager(trustManagers));
  9. } else{
  10. trustManager = new UnSafeTrustManager();
  11. }
  12. sslContext.init(keyManagers, new TrustManager[]{trustManager}, new SecureRandom());
  13. return sslContext.getSocketFactory();
  14. } catch (NoSuchAlgorithmException e){
  15. throw new AssertionError(e);
  16. } catch (KeyManagementException e){
  17. throw new AssertionError(e);
  18. } catch (KeyStoreException e){
  19. throw new AssertionError(e);
  20. }
  21. }
  22. private class UnSafeHostnameVerifier implements HostnameVerifier{
  23. @Override
  24. public boolean verify(String hostname, SSLSession session){
  25. return true;
  26. }
  27. }
  28. private static class UnSafeTrustManager implements X509TrustManager{
  29. @Override
  30. public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException{}
  31. @Override
  32. public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException{}
  33. @Override
  34. public X509Certificate[] getAcceptedIssuers(){
  35. return new X509Certificate[]{};
  36. }
  37. }
  38. private static TrustManager[] prepareTrustManager(InputStream... certificates){
  39. if (certificates == null || certificates.length <= 0) return null;
  40. try{
  41. CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
  42. KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
  43. keyStore.load(null);
  44. int index = 0;
  45. for (InputStream certificate : certificates){
  46. String certificateAlias = Integer.toString(index++);
  47. keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
  48. try{
  49. if (certificate != null)
  50. certificate.close();
  51. } catch (IOException e){
  52. }
  53. }
  54. TrustManagerFactory trustManagerFactory = null;
  55. trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  56. trustManagerFactory.init(keyStore);
  57. TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  58. return trustManagers;
  59. } catch (NoSuchAlgorithmException e){
  60. e.printStackTrace();
  61. } catch (CertificateException e){
  62. e.printStackTrace();
  63. } catch (KeyStoreException e){
  64. e.printStackTrace();
  65. } catch (Exception e){
  66. e.printStackTrace();
  67. }
  68. return null;
  69. }
  70. private static KeyManager[] prepareKeyManager(InputStream bksFile, String password){
  71. try{
  72. if (bksFile == null || password == null) return null;
  73. KeyStore clientKeyStore = KeyStore.getInstance("BKS");
  74. clientKeyStore.load(bksFile, password.toCharArray());
  75. KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  76. keyManagerFactory.init(clientKeyStore, password.toCharArray());
  77. return keyManagerFactory.getKeyManagers();
  78. } catch (KeyStoreException e){
  79. e.printStackTrace();
  80. } catch (NoSuchAlgorithmException e){
  81. e.printStackTrace();
  82. } catch (UnrecoverableKeyException e){
  83. e.printStackTrace();
  84. } catch (CertificateException e){
  85. e.printStackTrace();
  86. } catch (IOException e){
  87. e.printStackTrace();
  88. } catch (Exception e){
  89. e.printStackTrace();
  90. }
  91. return null;
  92. }
  93. private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers){
  94. for (TrustManager trustManager : trustManagers){
  95. if (trustManager instanceof X509TrustManager){
  96. return (X509TrustManager) trustManager;
  97. }
  98. }
  99. return null;
  100. }
  101. private static class MyTrustManager implements X509TrustManager{
  102. private X509TrustManager defaultTrustManager;
  103. private X509TrustManager localTrustManager;
  104. public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException{
  105. TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  106. var4.init((KeyStore) null);
  107. defaultTrustManager = chooseTrustManager(var4.getTrustManagers());
  108. this.localTrustManager = localTrustManager;
  109. }
  110. @Override
  111. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException{}
  112. @Override
  113. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException{
  114. try{
  115. defaultTrustManager.checkServerTrusted(chain, authType);
  116. } catch (CertificateException ce){
  117. localTrustManager.checkServerTrusted(chain, authType);
  118. }
  119. }
  120. @Override
  121. public X509Certificate[] getAcceptedIssuers(){
  122. return new X509Certificate[0];
  123. }
  124. }
复制代码

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

3.step

设置OkhttpClient。

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

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

  1. public static SSLSocketFactory getSSlFactory(Context context) {
  2. try {
  3. CertificateFactory cf = CertificateFactory.getInstance("X.509");
  4. InputStream caInput = new BufferedInputStream(context.getAssets().open("client.cer"));//把证书打包在asset文件夹中
  5. Certificate ca;
  6. try {
  7. ca = cf.generateCertificate(caInput);
  8. LogUtil.d("Longer", "ca=" + ((X509Certificate) ca).getSubjectDN());
  9. LogUtil.d("Longer", "key=" + ((X509Certificate) ca).getPublicKey());
  10. } finally {
  11. caInput.close();
  12. }
  13. // Create a KeyStore containing our trusted CAs
  14. String keyStoreType = KeyStore.getDefaultType();
  15. KeyStore keyStore = KeyStore.getInstance(keyStoreType);
  16. keyStore.load(null, null);
  17. keyStore.setCertificateEntry("ca", ca);
  18. // Create a TrustManager that trusts the CAs in our KeyStore
  19. String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
  20. TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
  21. tmf.init(keyStore);
  22. // Create an SSLContext that uses our TrustManager
  23. SSLContext s = SSLContext.getInstance("TLSv1", "AndroidOpenSSL");
  24. s.init(null, tmf.getTrustManagers(), null);
  25. return s.getSocketFactory();
  26. } catch (CertificateException e) {
  27. e.printStackTrace();
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. } catch (NoSuchAlgorithmException e) {
  31. e.printStackTrace();
  32. } catch (KeyStoreException e) {
  33. e.printStackTrace();
  34. } catch (KeyManagementException e) {
  35. e.printStackTrace();
  36. } catch (NoSuchProviderException e) {
  37. e.printStackTrace();
  38. }
  39. return null;
  40. }
复制代码

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

Glide 访问Https的图片

1.step

在build.gradle 引入下面的aar

  1. /提供的Module/
  2. compile 'com.github.bumptech.glide:okhttp3-integration:1.4.0@aar'
复制代码

2.step

  1. OkHttpClient okhttpClient = new OkHttpClient.Builder()
  2. .connectTimeout(30, TimeUnit.SECONDS)
  3. .retryOnConnectionFailure(true) //设置出现错误进行重新连接。
  4. .connectTimeout(15, TimeUnit.SECONDS)
  5. .readTimeout(60 * 1000, TimeUnit.MILLISECONDS)
  6. .sslSocketFactory(HttpsUtils.getSslSocketFactory(null,null,null))
  7. .hostnameVerifier(new HostnameVerifier() {
  8. @Override
  9. public boolean verify(String hostname, SSLSession session) {
  10. return true;
  11. }
  12. })
  13. .build();
  14. //让Glide能用HTTPS
  15. Glide.get(this).register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okhttpClient));
复制代码

设置已经验证证书的的OkhttpClient 到Glide 既可。

总结

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



回复

使用道具 举报

关闭

站长推荐上一条 /1 下一条