package com.skr.mdm.util;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.InputStream;
import java.security.KeyStore;

public class SSLUtil {

    public static SSLContext createSSLContext(String type, String path, String password) throws Exception {
        // "JKS"
        KeyStore ks = KeyStore.getInstance(type);
        // 证书存放地址
        InputStream ksInputStream = SSLUtil.class.getClassLoader().getResourceAsStream(path);
        ks.load(ksInputStream, password.toCharArray());
        // KeyManagerFactory充当基于密钥内容源的密钥管理器的工厂。
        // getDefaultAlgorithm:获取默认的 KeyManagerFactory 算法名称。
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, password.toCharArray());

        // 信任库
        TrustManagerFactory tf = null;
        String caPath = path;
        InputStream tIn = null;
        if (caPath != null) {
            KeyStore tks = KeyStore.getInstance(type);
            tIn = SSLUtil.class.getClassLoader().getResourceAsStream(caPath);
            tks.load(tIn, password.toCharArray());
            tf = TrustManagerFactory.getInstance("SunX509");
            tf.init(tks);
        }

        //SSLContext的实例表示安全套接字协议的实现，它充当用于安全套接字工厂或 SSLEngine 的工厂
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), tf.getTrustManagers(), null);
        return sslContext;
    }


}
