我正在尝试在单元测试中测试我的 SSL 实现,但有一种情况我不太理解。
当我连接到主机一次并失败时,后续的每个连接也会失败,即使它具有正确的证书。我假设在某个地方我必须刷新缓存。
这是我的代码,服务器和客户端都在本地运行。我对 trustStore 和 keyStore 使用一个 jks-File。无论最初的错误是什么,都会发生错误,下次我总是会收到第一个错误。
如果我不执行第一个请求,第二个请求就会起作用。
如果您想知道这里的用例是什么,我们有一些本地服务器使用来自内部 PKI 的 https 证书,当有人错误配置服务器或证书时,我们希望能够明显地更改它们,而无需关闭整个虚拟机。
//attempt a connection without certificates, will fail
try (final InputStream stream = new URL("https://localhost:" + port).openStream()){
System.out.println(IOUtils.toString(stream, Charset.defaultCharset()));
} catch (IOException e){
System.out.println("Failed to load: " + StackTraceUtil.getStackTrace(e));
}
//copies the jks file to a temporary location
final File jksFile = copyJKSFile();
//ignore host names, running locally, won't use this in production
HttpsURLConnection.setDefaultHostnameVerifier((hostname, sslSession) -> hostname.equalsIgnoreCase("localhost"));
//set the system properties
System.setProperty("javax.net.ssl.keyStore", jksFile.getAbsolutePath());
System.setProperty("javax.net.ssl.keyStorePassword", password);
System.setProperty("javax.net.ssl.trustStore", jksFile.getAbsolutePath());
System.setProperty("javax.net.ssl.trustStorePassword", password);
//this should work now
try (final InputStream stream = new URL("https://localhost:" + port).openStream()){
System.out.println(IOUtils.toString(stream, Charset.defaultCharset()));
} catch (IOException e){
System.out.println("Failed to load: " + StackTraceUtil.getStackTrace(e));
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
所以我找到了一个解决方案,我想我会分享它,以防其他人在某个时候遇到这个问题。
该类javax.net.ssl.HttpsURLConnection使用 ajavax.net.ssl.SSLSocketFactory来加载 Key- 和 TrustStore,后者javax.net.ssl.SSLContext在内部使用 a。当您不覆盖任何内容时,它会使用默认实现,该实现会加载文件并且加载后无法重置。
SSLContext因此,当我知道文件会更改时,我所做的不是使用默认实现,而是设置我自己的实现。
final SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
Run Code Online (Sandbox Code Playgroud)
如果您想使用旧版本的 TLS,完整列表应位于此处
| 归档时间: |
|
| 查看次数: |
2475 次 |
| 最近记录: |