package com.muzhi.dingtalk.test.http;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * 
 * @author shinka
 * @date 2021/02/25
 */
public class MyX509TrustManager implements X509TrustManager {

    private static MyX509TrustManager _instance = null;

    private SSLSocketFactory sslFactory = null;

    private MyX509TrustManager() {}

    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}

    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}

    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }

    /**
     * 获取SSL Socket工厂
     * <p>
     * Title: getSSLSocketFactory
     * </p>
     * 
     * @return
     */
    public SSLSocketFactory getSSLSocketFactory() {
        return sslFactory;
    }

    /**
     * 获取SSL管理助手类实例
     * <p>
     * Title: getInstance
     * </p>
     * 
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    @SuppressWarnings("static-access")
    synchronized public static MyX509TrustManager getInstance()
        throws NoSuchAlgorithmException, KeyManagementException {
        if (_instance == null) {
            _instance = new MyX509TrustManager();
            SSLContext sc = SSLContext.getInstance("SSLv3").getInstance("TLSv1.2");
            sc.init(null, new TrustManager[] {new MyX509TrustManager()}, null);
            _instance.sslFactory = sc.getSocketFactory();
        }
        return _instance;
    }
}
