我正在尝试使用Apache httpclient-4.5.5(使用httpcore-4.4.9)从应用“相互SSL”的服务器获取服务器证书。我正在创建一个SSLContext,如下所示:
final String keystorePass = Configuration.getInstance().getItem(EmittentProperties.keystorePass);
final String kmopEncKeyPass = Configuration.getInstance().getItem(EmittentProperties.kmopEncKeyPass);
final String kmopEncKeyAlias = Configuration.getInstance().getItem(EmittentProperties.kmopEncKeyAlias);
//1.Create the SSLContext and SSLConnectionSocketFactory
SSLContext sslContext;
try {
sslContext = SSLContexts.custom()
.loadKeyMaterial(keystoreFile.getFile(), keystorePass.toCharArray(), kmopEncKeyPass.toCharArray(), new PrivateKeyStrategy() {
@Override
public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
return kmopEncKeyAlias;
}})
.loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}})
.build();
} catch (Exception e) {
logger.error("Error initializing SSLContext: " + e.getMessage(), e);
throw new FatalException(e.getMessage(), e);
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
但是它始终在loadKeyMaterial(...)
上返回“java.security.UnrecoverableKeyException:无法恢复密钥”。
在调试此方法时,我可以看到他成功加载了密钥库,并且它包含我在其中创建的密钥。但是,当随后尝试加载与密码kmopEncKeyPass关联的密钥条目时,它将返回UnrecoverableKeyException。
我的(JKS)密钥库有两个(自签名)条目'kmop-enc'用于SSL握手,'kmop-sign'用于SSL签名消息。别名kmop-enc(参数kmopEncKeyPass)的密码与密钥库(参数keystorePass)的密码相同。使用自定义PrivateKeyStrategy,我想确保'kmop-enc'作为别名而不是'kmop-sign'(具有不同的密码)返回。
使用keystore-explorer.org验证我的密钥库显示我的密钥库一切正常。关于它为什么抛出UnrecoverableKeyException的任何想法?
答案 0 :(得分:0)
在致电.setKeyStoreType("JKS")
之前需要添加.loadKeyMaterial(...)
。