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

标签 java ssl keystore truststore jsse

我有一个在 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/

相关文章:

java - 从 CheckedTreeSelectionDialog 获取选定元素的建议

c# - 在 Azure 函数中使用 RestSharp 调用 HTTPS 会给出 "The SSL connection could not be established"

tomcat - keystore 文件未正确生成

android - 如何恢复丢失的 keystore 文件别名?

java - 从方法内的决策语句调用时 println 不会发生(在 Java 中)

java - 将输入从 JButton 传递到控制台

java - 加密字节后从 Cipher 获取更新的 IV

ssl - 一个 NFC 设备是否能够在不再次点击手机的情况下响应 P2P?

.htaccess - 在等待颁发 SSL 时临时重定向?

android - Unity SignReleaseBundle失败