Java tutorial
//package com.java2s; import java.io.BufferedInputStream; import java.io.InputStream; import java.security.KeyStore; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; import javax.security.auth.x500.X500Principal; public class Main { /** * Creates an SSLSocketFactory which contains {@code certChainFile} as its only root certificate. */ public static SSLSocketFactory newSslSocketFactoryForCa(InputStream certChain) throws Exception { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(new BufferedInputStream(certChain)); X500Principal principal = cert.getSubjectX500Principal(); ks.setCertificateEntry(principal.getName("RFC2253"), cert); // ks.setCertificateEntry("ca", cert); // Set up trust manager factory to use our key store. TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(ks); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, trustManagerFactory.getTrustManagers(), null); return context.getSocketFactory(); } }