使用 SSL 连接到 Kafka 集群时获取 PKIX 路径构建失败异常与 Apache Camel

Getting PKIX path building failed Exception with Apache Camel while connecting to the Kafka cluster with SSL

当我使用带 SSL 的 apache camel 连接到 Kafka 集群时,我遇到了以下问题,任何人都可以帮助解决这个问题

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1937) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296) at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1478) at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:212) at sun.security.ssl.Handshaker.processLoop(Handshaker.java:957) at sun.security.ssl.Handshaker.process_record(Handshaker.java:892) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1050) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1363) at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:735) at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)

// 加载.jks 文件的方式是否正确?

  @Component
    public class MyRouteDefinition extends RouteBuilder {
    
    @Override
    public void configure() throws Exception {

        KeyStoreParameters ksp = new KeyStoreParameters();
        ksp.setType("jks");
        ksp.setResource("truststore.jks);
        ksp.setPassword("password");

        KeyManagersParameters kmp = new KeyManagersParameters();
        kmp.setKeyStore(ksp);
        kmp.setKeyPassword("password");

        TrustManagersParameters trustManagersParameters = new TrustManagersParameters();
        trustManagersParameters.setKeyStore(ksp);

        SSLContextParameters scp = new SSLContextParameters();
        scp.setKeyManagers(kmp);
        scp.setTrustManagers(trustManagersParameters);

        HttpComponent httpComponent = getContext().getComponent("https4", HttpComponent.class);
        httpComponent.setSslContextParameters(scp);

        //TO HTTPS
        from(...)
        .to("https://localhost:8080/load")
             log.debug("The response code is: {}", responseCode);
         }
    }

当您使用 HTTPs 时,客户端需要信任服务器。服务器发送证书以证明其身份。证书由 CA(证书颁发机构)签署。客户端只有在识别出签署其证书的 CA 时才会信任服务器。如果 CA 存在于其信任库中,则客户端识别该 CA。

如果证书不是由 CA 签名的,您也可以直接将证书导入信任库。

我猜你需要

  1. 将签署服务器(侦听localhost:8080)证书的 CA 导入客户端的信任库
  2. 将服务器的证书本身导入信任库。
System.setProperty("javax.net.ssl.trustStore", "C:\user\myTrustStore"); 
System.setProperty("javax.net.ssl.trustStorePassword", "123456"); 

我找到了解决方案,上面的代码运行良好