在同一JVM上设置多个信任库

我有一个在weblogic服务器上运行的Java应用程序。 该应用程序有两个不同的模块,使用SSL连接到外部Web服务 – 比如模块A和模块B.

模块A – 基于轴构建 – 使用信任库A Moudle B – 基于Spring-ws构建 – 使用信任库B.

模块A存在。 正在介绍模块B.

我需要能够根据调用的模块在JVM中动态设置信任库。

由于某些限制,我没有选项 – 创建自定义密钥管理器。 – 使用一个信任库

我尝试使用System.setProperty im Module B codebase来设置truststore。 但是,仅当模块B首先被调用时才有效。 例如 – 假设我重新启动JVM然后调用模块A – 它在JVM中设置它自己的信任库然后我调用模块B – 它失败 – 它没有在JVM中设置它自己的信任库,即使我已经使用过System.setProperty方法。

我错过了什么,或者只是System.setProperty不会覆盖现有的设置值。 如果是这样,我的选择在这里。

您可以在运行时动态加载受信任的密钥库。

// load your key store as a stream and initialize a KeyStore InputStream trustStream = ... KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); // if your store is password protected then declare it (it can be null however) char[] trustPassword = ... // load the stream to your store trustStore.load(trustStream, trustPassword); // initialize a trust manager factory with the trusted store TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustFactory.init(trustStore); // get the trust managers from the factory TrustManager[] trustManagers = trustFactory.getTrustManagers(); // initialize an ssl context to use these managers and set as default SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManagers, null); SSLContext.setDefault(sslContext); 

注意,因为SSLContext.getDefault()会返回您无法修改默认上下文,因此您必须创建一个新的上下文,初始化它然后将此上下文设置为默认值。

最重要的是,如果您愿意, 可以使用任意数量的信任存储。