Я пытаюсь реализовать аутентификацию клиента и сервера с помощью Apache HTTPClient и проверить ее с помощью самозаверяющего сертификата.Я попытался следовать нескольким учебникам и ответам на подобные вопросы здесь, но безуспешно.Я постарался максимально подробно описать все шаги, которые я делал, надеюсь, кто-то укажет, что я делаю неправильно:
Создан файл req.conf
для конфигурации
[req]
prompt=no
distinguished_name = req_distinguished_name
[ req_distinguished_name ]
O=selfSignedO
CN=selfSignedCn
DC=selfSignedDc
Сгенерированный закрытый ключ сервера и самозаверяющий сертификат
openssl req \
-config req.conf \
-x509 \
-newkey rsa:4096 \
-keyout server/server-private-key.pem \
-out server/server.crt \
-days 3650 \
-nodes
Создан склад ключей PKCS12, содержащий закрытый ключ исертификат, созданный на предыдущем шаге
openssl pkcs12 \
-export \
-out server/server-key-store.p12 \
-inkey server/server-private-key.pem \
-in server/server.crt
Допустим, я использовал пароль 123456
Сгенерирован закрытый ключ клиента и запрос на подпись сертификата
openssl req \
-config req.conf \
-new \
-newkey rsa:4096 \
-out client/client-request.csr \
-keyout client/client-private-key.pem \
-nodes
Подписание запроса на подпись сертификата клиента с помощью закрытого ключа и сертификата сервера
openssl x509 \
-req \
-days 360 \
-in client/client-request.csr \
-CA server/server.crt \
-CAkey server/server-private-key.pem \
-CAcreateserial \
-out client/client-signed-cert.crt \
-sha256
Создание хранилища ключей PKCS12, содержащего закрытый ключ клиента, исертификат сертификата, созданный на предыдущем шаге.
openssl pkcs12 \
-export \
-out client/client-keystore.p12 \
-inkey client/client-private-key.pem \
-in client/client-signed-cert.crt \
-certfile server/server.crt
мы снова использовали 123456
в качестве пароля.
Сгенерированное доверенное хранилище сервера, содержащее подписанный сертификат клиента
keytool \
-import \
-trustcacerts \
-alias root \
-file client/client-signed-cert.crt \
-keystore server/server-trust-store.jks
пароль?123456
Завиток работает, но только с -k
curl -k \
--cert client/client-signed-cert.crt \
--key client/client-private-key.pem \
https://localhost:443:/my/endpoint
без -k
Я получаю ошибку:
curl: (60) SSL certificate problem: self signed certificate
More details here: https://curl.haxx.se/docs/sslcerts.html
curl performs SSL certificate verification by default, using a "bundle"
of Certificate Authority (CA) public keys (CA certs). If the default
bundle file isn't adequate, you can specify an alternate file
using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
the bundle, the certificate verification probably failed due to a
problem with the certificate (it might be expired, or the name might
not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
the -k (or --insecure) option.
HTTPS-proxy has similar options --proxy-cacert and --proxy-insecure.
Сконфигурированный Apache HTTPClient:
private HttpClient createClient() throws Exception {
String keyPassword = "123456";
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(resourceAsStream("/client/client-key-store.p12"), keyPassword.toCharArray());
SSLContext sslContext = new SSLContextBuilder()
.setProtocol("TLSv1.2")
.loadKeyMaterial(ks, keyPassword.toCharArray())
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build()
return HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
}
(Конструкция выполняется несколькими способами, которые я здесь сжал, поэтому, если что-то странное или отсутствует, пожалуйста, дайте мне знать, возможно,Я кое-что вставил.)