我有一个在 weblogic 服务器上运行的 Java 应用程序。该应用程序有两个不同的模块,它们使用 SSL 连接到外部 Web 服务 - 比如说模块 A 和模块 B。
模块 A - 基于 Axis 构建 - 使用信任库 A Moudle B - 基于 Spring-ws 构建 - 使用信任库 B。
模块 A 已存在。正在引入模块 B。
我需要能够根据正在调用的模块在 JVM 中动态设置信任库。
由于某些限制,我没有选择权 - 创建自定义 key 管理器。 - 使用一个信任库
我尝试使用 System.setProperty im 模块 B 代码库来设置信任库。但是,它仅在首先调用模块 B 时才有效。例如 - 说 我重新启动了 JVM 然后我调用模块 A - 它在 JVM 中设置了它自己的信任库 然后我调用模块 B - 它失败了 - 即使我使用了 System.setProperty 方法,它也没有在 JVM 中设置它自己的信任库。
我是不是遗漏了什么,或者只是 System.setProperty 没有覆盖现有的设置值。如果是这样,我的选择是什么。
最佳答案
您可以在运行时动态加载受信任的 key 存储。
// 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()
会返回您无法修改的默认上下文,所以您必须创建一个新的,初始化它然后将这个新的上下文设置为默认值。
最重要的是,如果您愿意,您可以使用任意数量的信任库。
关于java - 在同一个 JVM 上设置多个信任库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7591281/