Re: Trust CA cert without modifying keystore
Ian Pilcher wrote:
All of the example I can find involve using the keytool command to make
the CA certificate generally trusted by the system. I would much prefer
to simply embed the CA certificate in the application (as a String?) and
somehow create an SSL connection which trusts only this CA certificate.
OK, I figured it out. Here it is for posterity:
import java.security.cert.X509Certificate;
import java.security.cert.CertificateFactory;
import java.security.KeyStore;
import java.io.InputStream;
import java.io.FileImportStream;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.SSLSocket;
class MySSL
{
private static final String host = "my.host.name";
private static final int port = 443;
public static void main(String[] args) throws Exception
{
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream in = new FileInputStream("/my/CA/certificate.pem");
X509Certificate cert =
(X509Certificate)cf.generateCertificate(in);
in.close();
KeyStore ks = KeyStore.getInstance("jks");
ks.load(null, null);
ks.setCertificateEntry("My Certificate Authority", cert);
TrustManagerFactory tmf =
TrustManagerFactory.getInstance("PKIX");
tmf.init(ks);
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, tmf.getTrustManagers(), null);
SSLSocketFactory sf = context.getSocketFactory();
SSLSocket = (SSLSocket)sf.createSocket(host, port);
socket.startHandshake();
}
}
--
========================================================================
Ian Pilcher arequipeno@gmail.com
========================================================================