0

Question on the possibility to construct Java io.netty.handler.ssl.SslContext and org.apache.http.ssl.SSLContexts to trust certificates from multiple dynamic generated .pem files without a preloaded truststore.

In my case, I have 3 dynamically generated certificates, a root CA, an intermediate CA, another root CA, all in .pem format. (All starting with -----BEGIN CERTIFICATE----- )

I would like to create both the io.netty.handler.ssl.SslContext and org.apache.http.ssl.SSLContexts with the above generated certificates.

If possible, I would like to achieve this without creating a preloaded truststore.p12. Probably something like keytool -import -trustcacerts -file root_ca.pem -alias root-ca -keystore truststore.p12 And have a final truststore.p12 with everything, and have the app read the final truststore.p12 might work, but this is something I would like to avoid.

Is there a way to achieve the construction of both io.netty.handler.ssl.SslContext and org.apache.http.ssl.SSLContexts without a preloaded trust store, but directly from the .pem files?

Thank you

PatPanda
  • 3,644
  • 9
  • 58
  • 154

1 Answers1

2

Apache (for sure) uses the JSSE-provided TrustManager with minor tweaks. This TrustManager is actually initalized from a KeyStore object in memory that contains the certs; this KeyStore is often read in from a truststore file (or at least pseudo-file like a classloader resource), but need not be.

// prepare in standard JCA 
KeyStore ks = KeyStore.getInstance("PKCS12"); // type doesn't matter as long as it's filebased
ks.load(null);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
int counter = 0;
for( String f : new String[]{"pem1","pem2","pem3"} ){ // or other source(s) of data
    try( InputStream is = new FileInputStream(f) ){
        ks.setCertificateEntry("alias"+(++counter), cf.generateCertificate(is) );
        // or other aliases as long as they're unique, maybe even filenames
    }
}

// now use in Apache
SSLContext ctx = SSLContexts.custom().loadTrustMaterial(ks).build();
HttpClient client = HttpClientBuilder.create().setSSLContext(ctx)....build();

I expect more or less the same is true with netty, but I'm not familiar with it.

JCA CertificateFactory actually reads either PEM or DER, if you needed that.

dave_thompson_085
  • 34,712
  • 6
  • 50
  • 70