java Android OKHttp HTTPS 请求证书验证 PEM证书(1)

4 篇文章 0 订阅
3 篇文章 0 订阅

地址:http://blog.csdn.net/doubleping/article/details/53331864

调用new CustomTrust() 即可产生OkHttpClient

关键点:
1、将pem证书放入Raw或者assets目录。
2、证书的KeyStore读取方式。
3、HostnameVerifier过滤验证。

讲解: Pem 有多个 Certificate ,用CertificateFactory 读取 inputstream 为context.getResources().openRawResource(R.raw.a223)

1、证书读取详细:

   private SSLContext trustManagerForCertificates(InputStream in)
          throws GeneralSecurityException, IOException {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
    if (certificates.isEmpty()) {
      throw new IllegalArgumentException("expected non-empty set of trusted certificates");
    }

    // Put the certificates a key store.
    char[] password = CLIENT_KET_PASSWORD.toCharArray(); // Any password will work.
    KeyStore keyStore = newEmptyKeyStore(password);
    int index = 0;
    for (Certificate certificate : certificates) {
      String certificateAlias = Integer.toString(index++);
      keyStore.setCertificateEntry(certificateAlias, certificate);
    }

  //  keyStore.load(in,CLIENT_KET_PASSWORD.toCharArray());
    // Use it to build an X509 trust manager.
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
        KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
      throw new IllegalStateException("Unexpected default trust managers:"
          + Arrays.toString(trustManagers));
    }

    SSLContext ssContext = SSLContext.getInstance("SSL");
    ssContext.init(keyManagerFactory.getKeyManagers(),trustManagers,null);
    //return (X509TrustManager) trustManagers[0];
    return  ssContext;
  }


  private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
    try {
      KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
      InputStream in = null; // By convention, 'null' creates an empty key store.
      keyStore.load(in, password);
      return keyStore;
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }

2、SSLContext创建

关键:必须重写 HostnameVerifier 不然会出现javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated.错误,因为OKhttp 拥有默认的验证。

try {
    //  trustManager = trustManagerForCertificates(trustedCertificatesInputStream());
      SSLContext sslContext =  trustManagerForCertificates(trustedCertificatesInputStream()); //SSLContext.getInstance("TLS");
      sslSocketFactory = sslContext.getSocketFactory();
    } catch (GeneralSecurityException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      e.printStackTrace();
    }
    client = new OkHttpClient.Builder()
        .sslSocketFactory(sslSocketFactory).hostnameVerifier(new HostnameVerifier() {
              @Override
              public boolean verify(String hostname, SSLSession session) {
                return true;
              }
            })
        .build();

所有代码:将证书路径改动一下就可以直接使用了


import android.content.Context;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.Collection;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.CertificatePinner;
import okhttp3.OkHttpClient;

public final class CustomTrust {
  public static final String tag = "CustomTrust";
  private static final String CLIENT_KET_PASSWORD = "2342342342344433";
  public final OkHttpClient client;
  Context context;
  public CustomTrust(Context context)  {
    this.context = context;
    X509TrustManager trustManager;
    SSLSocketFactory sslSocketFactory=null;

    try {
    //  trustManager = trustManagerForCertificates(trustedCertificatesInputStream());
      SSLContext sslContext =  trustManagerForCertificates(trustedCertificatesInputStream()); //SSLContext.getInstance("TLS");
      sslSocketFactory = sslContext.getSocketFactory();
    } catch (GeneralSecurityException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      e.printStackTrace();
    }
    client = new OkHttpClient.Builder()
        .sslSocketFactory(sslSocketFactory).hostnameVerifier(new HostnameVerifier() {
              @Override
              public boolean verify(String hostname, SSLSession session) {
                return true;
              }
            })
        .build();

  }


  /**
   * Returns an input stream containing one or more certificate PEM files. This implementation just
   * embeds the PEM files in Java strings; most applications will instead read this from a resource
   * file that gets bundled with the application.
   */
  private InputStream trustedCertificatesInputStream() {
    // PEM files for root certificates of Comodo and Entrust. These two CAs are sufficient to view
    // https://publicobject.com (Comodo) and https://squareup.com (Entrust). But they aren't
    // sufficient to connect to most HTTPS sites including https://godaddy.com and https://visa.com.
    // Typically developers will need to get a PEM file from their organization's TLS administrator.

    return context.getResources().openRawResource(R.raw.qwww2) ;

    /*return new Buffer()
        .writeUtf8(comodoRsaCertificationAuthority)
        .writeUtf8(entrustRootCertificateAuthority)
        .inputStream();*/
  }

  /**
   * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose
   * certificates have not been signed by these certificates will fail with a {@code
   * SSLHandshakeException}.
   *
   * <p>This can be used to replace the host platform's built-in trusted certificates with a custom
   * set. This is useful in development where certificate authority-trusted certificates aren't
   * available. Or in production, to avoid reliance on third-party certificate authorities.
   *
   * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using
   * the host platform's built-in trust store.
   *
   * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>
   *
   * <p>Relying on your own trusted certificates limits your server team's ability to update their
   * TLS certificates. By installing a specific set of trusted certificates, you take on additional
   * operational complexity and limit your ability to migrate between certificate authorities. Do
   * not use custom trusted certificates in production without the blessing of your server's TLS
   * administrator.
   */
  private SSLContext trustManagerForCertificates(InputStream in)
          throws GeneralSecurityException, IOException {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
    if (certificates.isEmpty()) {
      throw new IllegalArgumentException("expected non-empty set of trusted certificates");
    }

    // Put the certificates a key store.
    char[] password = CLIENT_KET_PASSWORD.toCharArray(); // Any password will work.
    KeyStore keyStore = newEmptyKeyStore(password);
    int index = 0;
    for (Certificate certificate : certificates) {
      String certificateAlias = Integer.toString(index++);
      keyStore.setCertificateEntry(certificateAlias, certificate);
    }

  //  keyStore.load(in,CLIENT_KET_PASSWORD.toCharArray());
    // Use it to build an X509 trust manager.
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
        KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
      throw new IllegalStateException("Unexpected default trust managers:"
          + Arrays.toString(trustManagers));
    }

    SSLContext ssContext = SSLContext.getInstance("SSL");
    ssContext.init(keyManagerFactory.getKeyManagers(),trustManagers,null);
    //return (X509TrustManager) trustManagers[0];
    return  ssContext;
  }

  private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
    try {
      KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
      InputStream in = null; // By convention, 'null' creates an empty key store.
      keyStore.load(in, password);
      return keyStore;
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }

//  public static void main(String... args) throws Exception {
//    new CustomTrust().run();
//  }
}
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
OkHttp是一个开源的HTTP客户端库,用于在Android应用程序中进行网络请求。它提供了简洁的API,支持同步和异步请求,并具有高效的性能。 在使用OkHttp进行GET请求时,可以按照以下步骤进行操作: 1. 添加OkHttp库依赖:在项目的build.gradle文件中添加以下依赖项: ``` dependencies { implementation 'com.squareup.okhttp3:okhttp:4.9.0' } ``` 2. 创建OkHttpClient实例:使用OkHttpClient类创建一个HTTP客户端实例,可以设置一些配置参数,例如连接超时时间、读取超时时间等。 ```java OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .build(); ``` 3. 创建Request对象:使用Request类创建一个HTTP请求对象,指定请求的URL和请求方法(GET、POST等),可以添加一些请求头或请求参数。 ```java String url = "http://example.com/api/data"; Request request = new Request.Builder() .url(url) .get() .build(); ``` 4. 发送请求并获取响应:使用OkHttpClient的newCall方法发送请求,并通过Response对象获取服务器的响应结果。 ```java try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { String responseData = response.body().string(); // 处理响应数据 } else { // 处理请求失败情况 } } catch (IOException e) { e.printStackTrace(); } ``` 以上就是使用OkHttp进行GET请求的基本步骤。当然,还可以根据具体需求添加其他功能,例如设置请求头、请求参数、处理响应数据等。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值