Java Certificate Client SSL: unable to find valid certification path to requested target

落花浮王杯 提交于 2019-12-04 22:08:20

It has nothing to you with your client certificate. Your truststore doesn't trust the server certificate.

  1. Use openssl to generate your P12 file

    openssl pkcs12 -export -in /Users/me/test.authclient.int.com.crt -inkey /Users/me/test.authclient.int.com.key -out authClient.p12 -name authClientCert

  2. Generate the trust store key

    keytool -genkey -dname "cn=CLIENT" -alias trustStoreKey -keyalg RSA -keystore authClient-truststore.jks -keypass mypassword -storepass mypassword

  3. Now, import the trust store key

    keytool -import -keystore authClient-truststore.jks -file /Users/me/test.authclient.int.com/test.authclient.int.com.crt -alias.test.authclient.int.com

  4. Get the remote cert

    openssl x509 -in <(openssl s_client -connect the.ssl.api.i.want.to.call.com:443 -prexit 2>/dev/null) -out the.api.i.want.to.call.crt

  5. Add the server cert to the trust store

    keytool -importcert -file the.api.i.want.to.call.crt -alias the.api.i.want.to.call.com -keystore /Users/me/authClient-truststore.jks -storepass mypassword

Here's the client that I used to call the api that needed authentication.

    KeyStore clientStore = KeyStore.getInstance("PKCS12");
    clientStore.load(new FileInputStream("/Users/me/authClient.p12"), "mypassword".toCharArray());

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(clientStore, "mypassword".toCharArray());
    KeyManager[] keyManagers = kmf.getKeyManagers();

    KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(new FileInputStream("/Users/me/authClient-truststore.jks"), "mypassword".toCharArray());

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    TrustManager[] tms = tmf.getTrustManagers();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, tms, new SecureRandom());

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    HttpGet httpget = new HttpGet(requestUrl);

    httpclient.execute(httpget);

That't it. Let me know if I can help by expanding, but this should be all you need.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!