java 默认 SSL 上下文初始化失败:空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3927733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:59:54  来源:igfitidea点击:

Default SSL context init failed: null

javassl

提问by Sydney

When creating a SSL server, I got this exception: Default SSL context init failed: null. It seems that it comes from the fact it can't find the keystore and truststore. I try to set them from a jar file. The file exists in the jar but it seems that the resource cannot be found.

创建 SSL 服务器时,出现以下异常:Default SSL context init failed: null. 似乎是因为找不到密钥库和信任库。我尝试从 jar 文件中设置它们。该文件存在于 jar 中,但似乎找不到该资源。

String keystore = TestFramework.class.getResource("/security/keystore.jks").getFile();
System.setProperty("javax.net.ssl.keyStore", keystore);
System.setProperty("javax.net.ssl.keyStorePassword", password);
String truststore = TestFramework.class.getResource("/security/truststore").getFile();
System.setProperty("javax.net.ssl.trustStore", truststore);
System.setProperty("javax.net.ssl.trustStorePassword", "ebxmlrr");

I ran a lscommand to check if the file exists. It exists. Then I check if the keystore.jks exists by running the command jar -tf myjar.jar | grep securityand it exists.

我运行了一个ls命令来检查文件是否存在。它存在。然后我通过运行命令检查 keystore.jks 是否存在jar -tf myjar.jar | grep security并且它存在。

security/
security/keystore.jks
security/truststore

My application is running under Tomcat.

我的应用程序在 Tomcat 下运行。

回答by laz

The reason that won't work is that those system properties are expecting a file on the actual filesystem, not from within an archive. You'd be better off creating your own SSLContextusing those keystore and trustore streams:

不起作用的原因是这些系统属性需要实际文件系统上的文件,而不是来自存档中的文件。您最好SSLContext使用这些 keystore 和 trustore 流创建自己的:

KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(TestFramework.class.getResourceAsStream("/security/keystore.jks"), password.toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, password.toCharArray());

KeyStore trustStore = KeyStore.getInstance("jks");
trustStore.load(TestFramework.class.getResourceAsStream("/security/truststore"), "ebxmlrr".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(trustStore);

SSLContext context = SSLContext.getInstance("SSL");
context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());

...

HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());