尝试实现客户端密钥身份验证(使用自签名ca)。
代码如下:
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream("client.p12"), "changeit".toCharArray())
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy()) //DONT DO THAT, IT'S JUST TO SIMPLIFY THIS EXAMPLE. USE REAL TrustStore WITH REAL SERVER CERTIFICATE IMPORTED. DONT TRUST SELF SIGNED
.loadKeyMaterial(keyStore, "changeit".toCharArray())
.build();
socketFactory = new SSLConnectionSocketFactory(
sslcontext,
new String[] {"TLSv1.2", "TLSv1.1"},
null,
new NoopHostnameVerifier()
);
HttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(socketFactory)
.build();
使用-Djavax.net.debug=all
我可以看到它正确地选择我的证书,我看到签名,我看到证书请求,并且有ECDHClientKeyExchange等,一切看起来都很好。
但是无论如何我得到Nginx的响应(状态为400):
<head><title>400 The SSL certificate error</title></head>
请注意,对于不正确的证书/密钥,nginx通常会丢弃会话,而不提供纯文本响应中的任何详细信息。
此client.p12
可以从命令行运行,如:
$ curl -ivk --cert client.p12:changeit https://192.168.1.1
* Rebuilt URL to: https://192.168.1.1/
* Trying 192.168.1.1...
* Connected to 192.168.1.1 (192.168.1.1) port 443 (#0)
* WARNING: SSL: Certificate type not set, assuming PKCS#12 format.
* Client certificate: client-es.certs.my
* TLS 1.2 connection using TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
* Server certificate: server.certs.my
* Server certificate: ca.my
> GET / HTTP/1.1
> Host: 192.168.1.1
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 200 OK
所以这个密钥绝对有效。但为什么它不适用于Java?在java ssl config中有什么我错过的吗?
答案 0 :(得分:2)
问题是我的客户端密钥还包括在密钥链中签署证书。不仅是我的客户证书(认证所需),还有整个证书链(当然没有密钥,只有证书)
是:
> Root CA cert -> Client CA cert -> Client key + cert
我猜Java在这种情况下使用了错误的证书,可能是CA或中间证书。
通过向p12
或keychain
仅添加客户的密钥和证书来修复,无需中间人。
它不应该拥有-certfile
个选项(我以前拥有)。只是客户端密钥/证书。正确的导出命令是:
openssl pkcs12 -export \
-in client.crt -inkey client.key \
-out client.p12
然后可以将此client.p12
导入到钥匙串中:
keytool -importkeystore \
-deststorepass changeit -destkeystore keystore \
-srckeystore client.p12 -srcstoretype PKCS12 -srcstorepass changeit
并且可以自定义身份验证。