All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.net.wanmo.common.http.jdk.ssl.SSLContextFactory Maven / Gradle / Ivy

There is a newer version: 1.1.1
Show newest version
package cn.net.wanmo.common.http.jdk.ssl;


import cn.net.wanmo.common.util.StringUtil;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

public class SSLContextFactory {
    public static SSLContext createSSLContext(String certFilePath,String password) throws Exception {
        TrustManager[] trustManagers=null;
        if (StringUtil.isBlank(certFilePath)){
            trustManagers=new TrustManager[]{new MyTrustManager()};
        }else {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            FileInputStream inputStream = new FileInputStream(certFilePath);
            if(certFilePath.endsWith(".jks")){
                keyStore.load(inputStream, password.toCharArray());
                inputStream.close();
            }else {
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(inputStream);
                keyStore.load(null, null);
                keyStore.setCertificateEntry("myCert", cert);
            }
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
            trustManagerFactory.init(keyStore);
            trustManagers = trustManagerFactory.getTrustManagers();
        }
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);
        return sslContext;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy