OKHttp HTTPS 请求证书验证 PEM证书
来源:互联网 发布:华为云计算部门北京 编辑:程序博客网 时间:2024/05/01 07:17
调用new CustomTrust() 即可产生OkHttpClient
关键点:
1、将pem证书放入Raw或者assets目录。
2、证书的KeyStore读取方式。
3、HostnameVerifier过滤验证。
讲解: Pem 有多个 Certificate ,用CertificateFactory 读取 inputstream 为context.getResources().openRawResource(R.raw.a213679301700631)
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); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
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();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
所有代码:将证书路径改动一下就可以直接使用了
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 = "213679301700631"; 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.a213679301700631) ; /*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();// }
}
PFX Load 关键代码
...KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(in, password);.....TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm());trustManagerFactory.init(keyStore); SSLContext ssContext = SSLContext.getInstance("TLS");ssContext.init(null,trustManagers,null); ...client = new OkHttpClient.Builder() .sslSocketFactory(sslSocketFactory).hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }) .build();...
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
完整代码:
import android.content.Context;import java.io.IOException;import java.io.InputStream;import java.security.GeneralSecurityException;import java.security.KeyStore;import java.util.Arrays;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 = "213679301700631"; public final OkHttpClient client; Context context; public CustomTrust(Context context) { this.context = context; X509TrustManager trustManager; SSLSocketFactory sslSocketFactory=null;// trustManager = new X509TrustManager() {// @Override// public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {//// }//// @Override// public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {//// }//// @Override// public X509Certificate[] getAcceptedIssuers() {// return new X509Certificate[0];// }// }; try { // trustManager = trustManagerForCertificates(trustedCertificatesInputStream()); SSLContext sslContext = trustManagerForCertificates(trustedCertificatesInputStream()); //SSLContext.getInstance("TLS"); // sslContext = SSLContext.getInstance("SSL"); // sslContext.init(null,new X509TrustManager[]{trustManager},null); 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.b213679301700631) ; /*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 { // Put the certificates a key store. char[] password = CLIENT_KET_PASSWORD.toCharArray(); // Any password will work. KeyStore keyStore = newEmptyKeyStore(password); 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("TLS"); ssContext.init(keyManagerFactory.getKeyManagers(),trustManagers,null); return ssContext; } private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); 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();// }}
不对客户端证书校验,默认通过所有的验证。
import android.content.Context;import java.security.GeneralSecurityException;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSession;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.X509TrustManager;import okhttp3.OkHttpClient;public final class CustomTrust { public static final String tag = "CustomTrust"; private static final String CLIENT_KET_PASSWORD = "213679301700631"; public final OkHttpClient client; Context context; public CustomTrust(Context context) { this.context = context; X509TrustManager trustManager; SSLSocketFactory sslSocketFactory=null; trustManager = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; try { SSLContext sslContext; sslContext = SSLContext.getInstance("SSL"); sslContext.init(null,new X509TrustManager[]{trustManager},null); sslSocketFactory = sslContext.getSocketFactory(); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } client = new OkHttpClient.Builder() .sslSocketFactory(sslSocketFactory).hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }) .build(); }}
0 0
- OKHttp HTTPS 请求证书验证 PEM证书
- java Android OKHttp HTTPS 请求证书验证 PEM证书(1)
- OKHttp HTTPS 请求支持所有Https服务器 证书验证忽略客户端证书,(3)
- https 证书验证 okhttp https设置
- okhttp使用https忽略证书验证
- okhttp使用https忽略证书验证
- okhttp和webview跳过https证书验证
- okHttp 使用HTTPS证书
- iOS https请求 忽略证书验证
- Https请求忽略证书验证最新实现
- httpclient忽略证书验证允许https请求
- 验证 HTTPS 请求的证书(五)
- AFNetworking 3.0 https请求忽略证书验证
- 验证 HTTPS 请求的证书(五)
- 验证 HTTPS 请求的证书(五)
- Https请求忽略证书验证最新实现
- java androidOKHttp HTTPS 请求证书验证 PFX证书(2)
- Android下OkHttp请求自定义HTTPS证书接口设置
- 关于web开发中的规范流程
- 从UDP的”连接性”说起–告知你不为人知的UDP
- golang字符串首字母转化为大写
- Callable和Future
- POJ 2155 树状数组
- OKHttp HTTPS 请求证书验证 PEM证书
- SpannableStringBuilder实现图文混排
- Android中的DrawRect()参数解析
- 16进制、10进制、字符串、中文、byte[]相互转换--->java版
- Sublime text3 搭建python环境进行数据处理
- 查看手机是否安装微信客户端
- ACM篇:Codeforces 460 B -- Little Dima and Equation
- 关于iOS全面https,2017年1月1日开启ATS审核
- [iOS 启动图不显示] Launch Image和Launch Screen [转]