gpt4 book ai didi

java - 在 Java 中恢复 SSL X509TrustManager

转载 作者:太空宇宙 更新时间:2023-11-03 13:34:05 25 4
gpt4 key购买 nike

我有以下代码有条件地(基于 boolean)禁用 SSL 证书检查。

但是,如果我将 boolean 设置为 false 并重新运行我的代码,SSL 检查似乎仍然被禁用(当它应该被重新启用时) .

那么,与此相反的逻辑是什么,从而恢复检查?

if (bIgnoreSSL) {
TrustManager[] trustAllCertificates = new TrustManager[] {
new X509TrustManager()
{
@Override
public X509Certificate[] getAcceptedIssuers() { return null; // Not relevant.}

@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) { // Do nothing. Just allow them all. }

@Override
public void checkServerTrusted(X509Certificate[] certs, String authType){ // Do nothing. Just allow them all.}
}
};

HostnameVerifier trustAllHostnames = new HostnameVerifier()
{
@Override
public boolean verify(String hostname, SSLSession session) { return true; // Just allow them all. }
};

try
{
System.setProperty("jsse.enableSNIExtension", "false");
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCertificates, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
}
catch (GeneralSecurityException e)
{
throw new ExceptionInInitializerError(e);
}
}
else {
// Code to restore here (Opposite of above?)
}

最佳答案

一种替代方法是先将默认值保存在变量中,以便稍后恢复它们:

// save defaults (do this before setting another defaults)
HostnameVerifier defaultVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
SSLSocketFactory defaultFactory = HttpsURLConnection.getDefaultSSLSocketFactory();

if (bIgnoreSSL) {
...
} else {
// restore defaults
HttpsURLConnection.setDefaultHostnameVerifier(defaultVerifier);
HttpsURLConnection.setDefaultSSLSocketFactory(defaultFactory);
}

另一种选择(更好的选择,IMO)是为所有连接设置默认值,而是为每个单独的连接设置:

HttpsURLConnection conn = // create connection

if (bIgnoreSSL) {
// set custom verifier and factory only for this connection
conn.setHostnameVerifier(trustAllHostnames);
conn.setSSLSocketFactory(sc.getSocketFactory());
}
// no need to restore (else), as I didn't change the defaults

这只会更改指定连接的 validator 和工厂,而不会影响默认值(因此无需恢复)。

关于java - 在 Java 中恢复 SSL X509TrustManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45758605/

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