如何在jar中使用文件作为javax.net.ssl.keystore?

我正在尝试做类似的事情

URL clientks = com.messaging.SubscriptionManager.class.getResource( "client.ks" );

String path = clientks.toURI().getPath();

System.setProperty( "javax.net.ssl.keyStore", path);

其中client.ks是我正在运行的jar文件中com / messaging中存储的文件。

读取javax.net.ssl.keyStore的对象期望jar中的client.ks文件的路径。如果可能的话,我宁愿不提取文件并将其放在客户端的计算机上。那么可以在jar中引用文件吗?

这不起作用,因为getPath()返回null。还有另一种方法吗?

回答:

仍在实施中,但我相信可以通过InputStream从jar中加载密钥库,并以编程方式显式设置TrustStore(与设置System属性相对)。

得到它的工作!

InputStream keystoreInput = Thread.currentThread().getContextClassLoader()

.getResourceAsStream(<path in jar>/client.ks");

InputStream truststoreInput = Thread.currentThread().getContextClassLoader()

.getResourceAsStream(<path in jar>/client.ts");

setSSLFactories(keystoreInput, "password", truststoreInput);

keystoreInput.close();

truststoreInput.close();

private static void setSSLFactories(InputStream keyStream, String keyStorePassword,

InputStream trustStream) throws Exception

{

// Get keyStore

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

// if your store is password protected then declare it (it can be null however)

char[] keyPassword = keyStorePassword.toCharArray();

// load the stream to your store

keyStore.load(keyStream, keyPassword);

// initialize a key manager factory with the key store

KeyManagerFactory keyFactory =

KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

keyFactory.init(keyStore, keyPassword);

// get the key managers from the factory

KeyManager[] keyManagers = keyFactory.getKeyManagers();

// Now get trustStore

KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

// if your store is password protected then declare it (it can be null however)

//char[] trustPassword = password.toCharArray();

// load the stream to your store

trustStore.load(trustStream, null);

// initialize a trust manager factory with the trusted store

TrustManagerFactory trustFactory =

TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

trustFactory.init(trustStore);

// get the trust managers from the factory

TrustManager[] trustManagers = trustFactory.getTrustManagers();

// initialize an ssl context to use these managers and set as default

SSLContext sslContext = SSLContext.getInstance("SSL");

sslContext.init(keyManagers, trustManagers, null);

SSLContext.setDefault(sslContext);

}

以上是 如何在jar中使用文件作为javax.net.ssl.keystore? 的全部内容, 来源链接: utcz.com/qa/416988.html

回到顶部