以编程方式从 PEM 获取密钥库
如何以编程方式从同时包含证书和私钥的 PEM 文件中获取密钥库?我正在尝试在 HTTPS 连接中向服务器提供客户端证书。我已经确认,如果我使用openssl和keytool来获取jks文件,则客户端证书可以正常工作,我动态加载该文件。我甚至可以通过动态读取p12(PKCS12)文件来使其工作。
我正在考虑使用BouncyCastle的PEMReader类,但我无法克服一些错误。我使用-Djavax.net.debug=all选项运行Java客户端,并使用调试LogLevel运行Apache Web服务器。我不知道该找什么。Apache 错误日志指示:
...
OpenSSL: Write: SSLv3 read client certificate B
OpenSSL: Exit: error in SSLv3 read client certificate B
Re-negotiation handshake failed: Not accepted by client!?
Java 客户机程序指示:
...
main, WRITE: TLSv1 Handshake, length = 48
main, waiting for close_notify or alert: state 3
main, Exception while waiting for close java.net.SocketException: Software caused connection abort: recv failed
main, handling exception: java.net.SocketException: Software caused connection abort: recv failed
%% Invalidated: [Session-3, TLS_RSA_WITH_AES_128_CBC_SHA]
main, SEND TLSv1 ALERT: fatal, description = unexpected_message
...
客户端代码:
public void testClientCertPEM() throws Exception {
String requestURL = "https://mydomain/authtest";
String pemPath = "C:/Users/myusername/Desktop/client.pem";
HttpsURLConnection con;
URL url = new URL(requestURL);
con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(getSocketFactoryFromPEM(pemPath));
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(false);
con.connect();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
while((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
con.disconnect();
}
public SSLSocketFactory getSocketFactoryFromPEM(String pemPath) throws Exception {
Security.addProvider(new BouncyCastleProvider());
SSLContext context = SSLContext.getInstance("TLS");
PEMReader reader = new PEMReader(new FileReader(pemPath));
X509Certificate cert = (X509Certificate) reader.readObject();
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(null);
keystore.setCertificateEntry("alias", cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keystore, null);
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, null);
return context.getSocketFactory();
}
我注意到服务器在日志中输出SSLv3,而客户端是TLSv1。如果我添加系统属性 -Dhttps.protocols=SSLv3,则客户端也将使用 SSLv3,但我收到相同的错误消息。我还尝试添加 -Dsun.security.ssl.allowUnsafeRenegotiation=true,结果没有变化。
我已经用谷歌搜索了一下,这个问题的通常答案是先使用openssl和keytool。就我而言,我需要直接在飞行中阅读PEM。我实际上正在移植一个已经这样做的C++程序,坦率地说,我非常惊讶在Java中做到这一点是多么困难。C++代码:
curlpp::Easy request;
...
request.setOpt(new Options::Url(myurl));
request.setOpt(new Options::SslVerifyPeer(false));
request.setOpt(new Options::SslCertType("PEM"));
request.setOpt(new Options::SslCert(cert));
request.perform();