cn.net.wanmo.common.http.ssl.SSLContextFactory Maven / Gradle / Ivy
package cn.net.wanmo.common.http.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;
}
}