HttpsUrlConnection 使用 KeyStore 而不是 TrustStore 与 WebSphere Liberty Profile

HttpsUrlConnection using KeyStore instead of TrustStore with WebSphere Liberty Profile

我们在 WebSphere Liberty Profile 的 WebSphere TAI 中使用 HttpsUrlConnection 连接到安全服务器。我在 SSL 证书错误方面遇到了很多问题,直到我发现它正在 WLP 密钥库中寻找签名者证书,而不是 WLP 信任库或 JVM 信任库。代码中没有设置这个,它必须是默认值。但是我很困惑,因为当我们在其他代码中使用 HTTP 客户端时,它使用了 JVM 的信任库。

如何让 HttpsUrlConnection 使用 WLP 或 JVM 信任库,而不是密钥库?

您可以如下加载您的信任库并将其设置为 SSLContext,后者可以设置到 HttpsUrlConnection 中。由于这是我使用默认值的示例,您应该将它们替换为适当的算法、协议和信任库类型。

        try (FileInputStream truststoreFile = new FileInputStream("path/to/your/truststore.jks")) {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType());
            char[] trustorePassword = "<truststorePassword".toCharArray();
            truststore.load(truststoreFile, trustorePassword);
            trustManagerFactory.init(truststore);
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            KeyManager[] keyManagers = {};//if you have key managers;

            sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), new SecureRandom());

            URL httpsUrl = new URL("<your https url>");
            URLConnection urlConnection = httpsUrl.openConnection();

        } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) {
            //handle exception
        } catch (KeyManagementException e) {
           //handle exception
        }