gpt4 book ai didi

java - 在 Java 运行时加载 CA 根证书

转载 作者:搜寻专家 更新时间:2023-11-01 03:01:56 25 4
gpt4 key购买 nike

tl;dr:使用自定义 CA 而不将其添加到永久 keystore 。

我正在编写一个应该使用 HTTPS 连接到远程服务器的 Java 应用程序。连接代码已准备就绪,但是服务器的 SSL 证书是由 StartSSL 签署的,它不在 Java 的 CA 根证书库中。

使用 this code ,我从 https://www.google.com/ 等网站获取有效的证书信息:

Response Code : 200
Cipher Suite : TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256

Cert Type : X.509
Cert Hash Code : -1643391404
Cert Public Key Algorithm : RSA
Cert Public Key Format : X.509

Cert Type : X.509
Cert Hash Code : 771393018
Cert Public Key Algorithm : RSA
Cert Public Key Format : X.509

Cert Type : X.509
Cert Hash Code : 349192256
Cert Public Key Algorithm : RSA
Cert Public Key Format : X.509

相同的代码为我的域抛出一个 SSLHandshakeException(我们称之为 https://www.example.com/)。

当然,我可以使用 keytool(甚至可以使用 Runtime.exec("keytool ..."))手动将证书添加到 keystore ,但这是弄脏的方式。我现在计划的是将 StartSSL 根证书添加到我的应用程序文件中以供分发,然后在运行时将其加载到某个临时 keystore 中。这样“真正的” keystore 保持不变。

从我读到的herehere ,我将不得不处理一些类,例如 TrustManager。我什至找到了 completely turn off the validation 的方法,但这不是我想要的,因为它似乎消除了加密通信的全部目的。

我什至发现一些代码行似乎完全符合我的要求,但我不知道如何调用此方法,即要将哪些值作为参数传递:

public class SSLClasspathTrustStoreLoader {
public static void setTrustStore(String trustStore, String password) throws Exception {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream keystoreStream = SSLClasspathTrustStoreLoader.class.getResourceAsStream(trustStore);
keystore.load(keystoreStream, password.toCharArray());
trustManagerFactory.init(keystore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustManagers, null);
SSLContext.setDefault(sc);
}
}

有没有人遇到过类似的情况?我将不胜感激有关如何处理此问题的任何建议。如果你能帮我运行上面的代码,我会很高兴!

最佳答案

您将需要创建一个您已经找到的自定义 TrustStore。除此之外,您还需要创建一个使用您提到的自定义信任管理器的自定义 SSL 套接字工厂,并将其注册到您正在使用的 HTTP 框架。细节实际上取决于您选择的框架。

使用 keytool 实用程序将证书添加到默认 keystore 没有任何问题。您可能会发现需要多个证书。如果是这种情况,您必须确保整个 Java 应用程序使用相同的 key 存储作为单一事实来源。如果您在同一个应用程序中使用多个 key 存储,它可能会变得非常棘手。

希望这对您有所帮助。

关于java - 在 Java 运行时加载 CA 根证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32851341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com