gpt4 book ai didi

java - SSLSocketFactory 忽略服务器证书

转载 作者:太空宇宙 更新时间:2023-11-03 15:16:18 26 4
gpt4 key购买 nike

我需要创建一个 javax.net.ssl.SSLSocketFactory 来建立 TLS 连接但忽略服务器证书的验证。不适用于 HTTP 协议(protocol)。我知道这不是正确的做法,但我需要它。我不想要也不喜欢。

我做了一个可行的实现,但验证服务器证书(因为它应该是)实现如下所示:

/**
* Provide a quick method to construct a SSLSocketFactory which is a TCP socket using TLS/SSL
* @param trustStore location of the trust store
* @param keyStore location of the key store
* @param trustStorePassword password to access the trust store
* @param keyStorePassword password to access the key store
* @return the SSLSocketFactory to create secure sockets with the provided certificates infrastructure
* @exception java.lang.Exception in case of something wrong happens
* */
static public SSLSocketFactory getSocketFactory ( final String trustStore, final String keyStore, final String trustStorePassword, final String keyStorePassword) throws Exception
{

// todo check if the CA needs or can use the password
final FileInputStream trustStoreStream = new FileInputStream(trustStore);
final FileInputStream keyStoreStream = new FileInputStream(keyStore);
// CA certificate is used to authenticate server
final KeyStore caKs = KeyStore.getInstance("JKS");
caKs.load(trustStoreStream, trustStorePassword.toCharArray());
final TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(caKs);

trustStoreStream.close();

// client key and certificates are sent to server so it can authenticate us
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(keyStoreStream, keyStorePassword.toCharArray());
final KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
kmf.init(ks, keyStorePassword.toCharArray());

keyStoreStream.close();

// finally, create SSL socket factory
final SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

return context.getSocketFactory();
}

最佳答案

解决方案是创建一个虚拟 X509TrustManager 类,它基本上接受所有服务器证书而不进行检查。

然后创建一个实例并将其作为 SSLContext::init 调用中的第二个参数传递。

但说真的,这是个坏主意。如果您不打算检查 CERT,则使用 SSL 毫无意义或更糟1


1 - 这是我的理论。您的安全人员告诉您,通过不安全的 channel 使用 MTTQ 是危险的。或者他们已经阻止了端口 1883。但是你有一个 MTTQ/SSL 服务器,你不会为获得适当的 CERT 而烦恼。所以你只是想把一些“有效”的东西放在一起。你猜怎么了。如果告诉您使用 SSL 的人发现了,他们会 have your guts for garters!如果您不是出于这个原因而这样做,那么……好吧……您所做的事情毫无意义。即使是自签名服务器 CERT 也比这更好。您只需将其添加为客户端 keystore 中的受信任证书。

关于java - SSLSocketFactory 忽略服务器证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49047805/

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