IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> OkHttp与WebView证书验证 -> 正文阅读

[网络协议]OkHttp与WebView证书验证

1、带证书验证

public class OkHttpManager {

    public static final String TAG = "OkHttpManager";

    /**
     * CERT_ALIAS  证书别名
     */
    public static final String CERT_ALIAS = "NCB";

    /**
     * 超时时间
     */
    public static final int CONNECT_TIME_OUT_60 = 60;
    public static final int READ_TIME_OUT_60 = 60;
    public static final int WRITE_TIME_OUT_60 = 60;
    public static final int CONNECT_TIME_OUT_10 = 10;
    public static final int READ_TIME_OUT_10 = 10;
    public static final int WRITE_TIME_OUT_10 = 10;

    /**
     * instance 单例
     * INSTANCE_LOCK 互斥锁
     */
    private static OkHttpManager instance = null;
    private static final Object INSTANCE_LOCK = new Object();


    /**
     * 获取单例
     *
     * @return
     */
    public static OkHttpManager getInstance() {
        if (instance == null) {
            synchronized (INSTANCE_LOCK) {
                if (instance == null) {
                    instance = new OkHttpManager();
                }
            }
        }
        return instance;
    }


    /**
     * 获取本地证书
     *
     * @return
     */
    public ArrayList<Certificate> getCertificatesFromAssets(Context context) {
        ArrayList<Certificate> certificates = new ArrayList<>();
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            AssetManager am = context.getAssets();
            //assets中的公共证书
            String certPathMain = "ncb_certs";
            String[] listMain = am.list(certPathMain);
            for (int i = 0; i < listMain.length; i++) {
                certificates.add(certificateFactory.generateCertificate(am.open(certPathMain + "/" + listMain[i])));
                LogUtils.i(TAG, "public cer name:" + certPathMain + "/" + listMain[i]);
            }
            //sit uat prod 中各自的证书
            String certPath = null;
            if (BuildConfig.FLAVOR.equals(BUILD_FLAVOR_PROD)) {
                certPath = "ncb_certs_prod";
            } else if (BuildConfig.FLAVOR.equals(BUILD_FLAVOR_SIT)) {
                certPath = "ncb_certs_sit";
            } else {
                certPath = "ncb_certs_uat";
            }
            String[] list = am.list(certPath);
            for (int i = 0; i < list.length; i++) {
                certificates.add(certificateFactory.generateCertificate(am.open(certPath + "/" + list[i])));
                LogUtils.i(TAG, "private cer name:" + certPath + "/" + list[i]);
            }
            //sit uat prod 的 certs文件夹中的证书
            certPath = "certs";
            String[] list_certs = am.list(certPath);
            for (int i = 0; i < list_certs.length; i++) {
                certificates.add(certificateFactory.generateCertificate(am.open(certPath + "/" + list_certs[i])));
                LogUtils.i(TAG, "certs name:" + certPath + "/" + list_certs[i]);
            }
            return certificates;
        } catch (Exception e) {
            if (BuildConfig.isLogDebug) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 获取含证书校验功能的 OkHttpClientBuilder
     *
     * @param context
     * @return
     */
    public OkHttpClient.Builder getOkHttpClientBuilderWithCerts(Context context, int connectTimeOut, int readTimeOut, int writeTimeOut) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        try {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            //本地证书
            ArrayList<Certificate> localCerts = getCertificatesFromAssets(context);
            for (int i = 0; i < localCerts.size(); i++) {
                keyStore.setCertificateEntry(CERT_ALIAS + i, localCerts.get(i));
            }

            SSLContext sslContext = SSLContext.getInstance("TLS");
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            final X509TrustManager 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];
                }
            };
            builder.sslSocketFactory(sslSocketFactory, trustManager);

            HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            builder.hostnameVerifier(hostnameVerifier);

            builder.connectTimeout(connectTimeOut, TimeUnit.SECONDS)
                    .readTimeout(readTimeOut, TimeUnit.SECONDS)
                    .writeTimeout(writeTimeOut, TimeUnit.SECONDS);


            return builder;
        } catch (Exception e) {
            if (BuildConfig.isLogDebug) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

2、忽略证书验证

public class OkHttpManager {

    public static final String TAG = "OkHttpManager";

    /**
     * CERT_ALIAS  证书别名
     */
    public static final String CERT_ALIAS = "NCB";

    /**
     * 超时时间
     */
    public static final int CONNECT_TIME_OUT_60 = 60;
    public static final int READ_TIME_OUT_60 = 60;
    public static final int WRITE_TIME_OUT_60 = 60;
    public static final int CONNECT_TIME_OUT_10 = 10;
    public static final int READ_TIME_OUT_10 = 10;
    public static final int WRITE_TIME_OUT_10 = 10;

    /**
     * instance 单例
     * INSTANCE_LOCK 互斥锁
     */
    private static OkHttpManager instance = null;
    private static final Object INSTANCE_LOCK = new Object();


    /**
     * 获取单例
     *
     * @return
     */
    public static OkHttpManager getInstance() {
        if (instance == null) {
            synchronized (INSTANCE_LOCK) {
                if (instance == null) {
                    instance = new OkHttpManager();
                }
            }
        }
        return instance;
    }

    /**
     * 不带证书验证的OkHttp
     *
     * @param context
     * @param connectTimeOut
     * @param readTimeOut
     * @param writeTimeOut
     * @return
     */
    public OkHttpClient.Builder getOkHttpClientBuilderNoCerts(Context context, int connectTimeOut, int readTimeOut, int writeTimeOut) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        try {
            final X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    X509Certificate[] x509Certificates = new X509Certificate[0];
                    return x509Certificates;
                }
            };
            SSLContext sslContext = null;
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{trustManager}, new SecureRandom());


            builder.sslSocketFactory(sslContext.getSocketFactory(), trustManager);

            HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            builder.hostnameVerifier(hostnameVerifier);

            builder.connectTimeout(connectTimeOut, TimeUnit.SECONDS)
                    .readTimeout(readTimeOut, TimeUnit.SECONDS)
                    .writeTimeout(writeTimeOut, TimeUnit.SECONDS);


            return builder;
        } catch (Exception e) {
            if (BuildConfig.isLogDebug) {
                e.printStackTrace();
            }
        }
        return null;
    }

}

WebView忽略本身自带证书验证

		webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                if (handler != null) {
                    handler.proceed();//忽略证书的错误继续加载页面内容,不会变成空白页面
                }
            }
        });
  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2022-02-22 20:59:39  更:2022-02-22 21:00:26 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 8:46:52-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码