android okhttps双向验证

使用:

  public void getHttps() {
        try {
            OkHttpClient mOkHttpClient = null;
            mOkHttpClient = new OkHttpClient().newBuilder()
//                    主要就是下面2句,其他的和正常请求都一样的
                    .hostnameVerifier(new Home())//忽略服务器域名不信任警告
                    .sslSocketFactory(MySSLSocketFactory.getSocketFactory(MainActivity.this))//加入证书
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    Log.e("tyl", "onFailure=" + e.getMessage());
                }
                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    Log.e("tyl", "onResponse=" + response.body().string());
                }
            });
        } catch (Exception e) {
            Log.e("tyl", "IOException=" + e);
            e.printStackTrace();
        }
    }

    public class Home implements HostnameVerifier {
        public SSLSession sslSession;

        @Override
        public boolean verify(String hostname, SSLSession session) {
            this.sslSession = session;
            return true;
        }
    }

证书文件放在:


android okhttps双向验证_第1张图片
证书文件位置

SSLSocketFactory:

package com.tgdz.my.testhttps;

import android.content.Context;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

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

/**
 * Created by tyl
 * 2018/7/9/009
 * Describe:
 */

public class MySSLSocketFactory {
    private static final String KEY_STORE_TYPE_BKS = "bks";//证书类型
    private static final String KEY_STORE_TYPE_P12 = "PKCS12";//证书类型
    private static final String KEY_STORE_PASSWORD = "123456";//证书密码(应该是客户端证书密码,没有密码的直接改为空字符串)
    private static final String KEY_STORE_TRUST_PASSWORD = "123456";//授信证书密码(应该是服务端证书密码)
    private static InputStream trust_input;
    private static InputStream client_input;

    public static SSLSocketFactory getSocketFactory(Context context)  {
//        可以使用bks和client.cer来验证 去掉注释的代码,client.p12替换ca.p12即可,也可以直接通过p12我测试的时候也是通过的
        try {
            //服务器授信证书
//            trust_input = context.getResources().getAssets().open("client.bks");
            //客户端证书
            client_input = context.getResources().getAssets().open("ca.p12");
            SSLContext sslContext = SSLContext.getInstance("TLS");
//            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
//            trustStore.load(trust_input, KEY_STORE_TRUST_PASSWORD.toCharArray());
//            KeyStore存放证书及密匙的仓库
            KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE_P12);
            keyStore.load(client_input, KEY_STORE_PASSWORD.toCharArray());
//            KeyManagerFactory证书管理类
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, KEY_STORE_PASSWORD.toCharArray());
//            核心代码 SSLContext此类的实例表示安全套接字协议的实现, 它是SSLSocketFactory、SSLServerSocketFactory和SSLEngine的工厂。
//            这里注意有一个坑,之前我写的时候参考的网上文档大部分都是使用的是TrustManager系统默认的证书管理器但是自建证书需要使用X509TrustManager来实现
            sslContext.init(keyManagerFactory.getKeyManagers(),new TrustManager[]{new TrustAllCerts()}, new SecureRandom());

            SSLSocketFactory factory = sslContext.getSocketFactory();

            return factory;

        } catch (Exception e) {
            e.printStackTrace();
                Log.e("tyl","Exception="+e.getMessage());
            return null;
        } finally {
            try {
//                trust_input.close();
                client_input.close();
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("tyl","Exception="+e.getMessage());
            }
        }
    }
};

X509TrustManager :

package com.tgdz.my.testhttps;

import android.util.Log;

import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

/**
 * Created by tyl
 * 2018/7/12/012
 * Describe:
 */


public class TrustAllCerts implements X509TrustManager {
//    默认的下面3个接口都会抛出一个异常,这里直接去掉异常,就是客户端忽略验证服务器端的验证信息直接通过
    @Override
    public void checkClientTrusted(
            X509Certificate[] chain, String authType) {
        Log.e("tyl","checkClientTrusted");
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) {
        Log.e("tyl","checkServerTrusted");
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        Log.e("tyl","getAcceptedIssuers");
        return new X509Certificate[]{};}
}

各类知识点整理:

  • android https双向验证 前言及总结:https://www.jianshu.com/p/07ce321d80ab
  • 单双向验证基础知识点: https://www.jianshu.com/p/ea5f4b1d9c00
  • phpstudy搭建本地服务器: https://www.jianshu.com/p/bbf853fc28f3
  • 浏览器获取证书文件(p12转cer):https://www.jianshu.com/p/7f74acab6c74
  • https双向认证证书生成:https://www.jianshu.com/p/094c7fc8cb85
  • android webView的双向验证:https://www.jianshu.com/p/e98119d04fd9
  • 配置完成后的测试:https://www.jianshu.com/p/cfcf708a591a
  • Glide okhttps证书验证全局配置:https://www.jianshu.com/p/ac0b5c5f3ca7

工具类:

  • P12证书转BKS证书:https://www.jianshu.com/p/2a96c36b27fe
  • 服务器网址检测(兼容性及协议检测):https://www.ssllabs.com/index.html

源码:

  • github:https://github.com/fs437563/android_https

你可能感兴趣的:(android okhttps双向验证)