将Java commons-httpclient与从.pfx中提取的cacert,cert和密钥一起使用

问题描述 投票:0回答:1

我输入了一个.pfx文件。

我使用以下命令从中提取CA证书,客户端证书和密钥:

openssl pkcs12 -in input.pfx -clcerts -nokeys -out client-cert.pem
openssl pkcs12 -in input.pfx -out ca-cert.pem -nodes -nokeys -cacerts
openssl pkcs12 -in input.pfx -nocerts -nodes -out client.key

现在我可以使用curl执行以下请求:

curl --cacert ./ca-cert.pem --key ./client.key --cert ./client-cert.pem -i -X POST --data-binary'@。/ my-data.txt'https://my-target.url

现在我想使用commons-httpclient在Java中执行相同的请求

据我所知,我应该将我的密钥转换为“keystore.jks”和“truststore.jks”并将其用作以下内容:

SSLContext sslContext = SSLContexts.custom()
   .loadTrustMaterial(new File("truststore.jks"), PASS.toCharArray())
   .loadKeyMaterial(new File("keystore.jks"), PASS.toCharArray(), PASS.toCharArray())
   .build();

CloseableHttpClient client = HttpClients.custom()
    .setSSLContext(sslContext)
    .build();

HttpPost post = new HttpPost("https://my-target.url");
post.setEntity(new ByteArrayEntity(FileUtils.readFileToByteArray(new File("my-data.txt"))));
client.execute(post);

有没有更简单的方法将证书传递给POST?如果没有,将.pfx转换为.jks的正确方法是什么?

我试过了

keytool -importkeystore -srckeystore input.pfx -srcstoretype pkcs12 -destkeystore keystore.jks -deststoretype JKS

但结束了

java.security.UnrecoverableKeyException:无法恢复密钥

java ssl curl apache-commons-httpclient jks
1个回答
0
投票

最终解决方案是直接加载pfx文件并在那里信任证书。

final KeyStore store = KeyStore.getInstance("PKCS12");

try (FileInputStream stream = new FileInputStream(new File("file.pfx"))) {
    store.load(stream, PASS.toCharArray());
}
SSLContext sslContext = SSLContexts.custom()
    .loadKeyMaterial(store, PASS.toCharArray())
    .loadTrustMaterial(store, TrustSelfSignedStrategy.INSTANCE)
    .build();
© www.soinside.com 2019 - 2024. All rights reserved.