默认SSL上下文init失败:null

创建SSL服务器时,出现此exception: 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"); 

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

 security/ security/keystore.jks security/truststore 

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

不起作用的原因是那些系统属性期望实际文件系统上的文件,而不是存档中的文件。 您最好使用这些密钥库和可信任流创建自己的SSLContext

 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());