Reputation: 431
The basic components of my question are (context follows code snippet)
Is there a better alternative to setting the default trust/key stores, at run-time, from a resource?
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(testService.class.getClassLoader().getResourceAsStream("resources/.keystore"), "changeit".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, "changeit".toCharArray());
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
SSLContext.setDefault(ctx);
The context surrounding this question is as follows. I am currently developing a CXF client for a web service with mutual certificate authentication. For various reasons, adding the client certificate and key to the default keystore is not a desirable option. Ideally, I was looking for a way include a keystore as a resource file in the JAR, and set it as the default at run-time, as the need arose. I also wanted to avoid configuring each client and/or connection on a per-object basis, and also support the operation of things such as JaxWsDynamicClientFactory (mostly for the sake of "completeness").
I scoured the internet and SO for relevant material and found these (one, two) related questions, but none of the solutions offered were exactly what I was looking for (although I did use them as a springboard to develop the code above).
Now, I realize that other solutions could be made to work, but I was/am specifically looking for a solution that would meet all of these requirements.
Upvotes: 7
Views: 21209
Reputation: 122739
Your code will use the same keystore (loaded from the classloader) as the default key store and the default trust store. That's effectively equivalent to setting both -Djavax.net.ssl.keystore*
and -Djavax.net.ssl.truststore*
with the same value.
This is fine if that's what you want to do. (You may want to close the InputStream
once you've loaded the keystore, though.)
This will affect the entire JVM, and everything that uses SSLContext.getDefault()
, in particular everything that relies on the default SSLSocketFactory
(URLConnection
and so on).
Since this will be your default trust store, the default trusted CA certificates from the major CAs won't be in your trust store unless you've also explicitly imported them into the copy you load from the classloader.
Presumably, you won't have a large number of new CA (or self-signed) certificates to trust. It might be more convenient to keep the keystore and truststore separated, since your truststore might be common to most of your clients, and it would usually just be a one-off configuration step at the beginning.
Upvotes: 8