java javax.net.ssl.keystore冲突解决?_如何在jar中使用文件作为javax.net.ssl.keystore?

本文介绍了一种通过编程方式从jar文件中加载Keystore和Truststore的方法,避免了直接设置系统属性的方式。该方法首先从当前线程的上下文类加载器中获取输入流,然后使用这些输入流来初始化KeyStore、KeyManagerFactory和TrustManagerFactory等组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小编典典

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

得到它的工作!

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

.getResourceAsStream(/client.ks");

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

.getResourceAsStream(/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);

}

2020-09-16

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值