Search code examples
javakeystoreca

java Temporarily adding CA seems to malfunction


Since not all jvm's have letsencrypt yet in their cacert keystore, I need to temporarily add it when running a program. My code is as follows:

public void addRootCA() throws Exception {
    InputStream fis = new BufferedInputStream(this.getClassLoader().getResourceAsStream("letsencrypt.crt"));
    Certificate ca = CertificateFactory.getInstance("X.509").generateCertificate(fis);
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null, null);
    ks.setCertificateEntry("LetsEncrypt CA", ca);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);
    HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
}

It does seem to add the certificate (the exceptions for it being missing disappears and I get a response on the serverside) but it seems that the other CA's from the default java key store aren't loaded anymore. I got the code mostly from another stackoverflow question that was marked as the right answer, so I am puzzled that it doesn't behave appropriately.

What is the reason that other CA's don't get loaded? Or is there maybe an entirely different problem?


Solution

  • The default Java keystore isn't loading because you aren't loading it. You're loading it from null which creates an empty keystore. You would need to locate the default Java keystore, open it, load from it, and close it.