GCP-PUBSUB:-sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径

Posted

技术标签:

【中文标题】GCP-PUBSUB:-sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径【英文标题】:GCP-PUBSUB:-sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target 【发布时间】:2020-06-15 02:52:20 【问题描述】:

我遇到了一个奇怪的问题。我创建了一个 pubsub 主题并将消息发布到主题。当我使用 java main 方法时,我可以成功发布消息,但是当我使用不同的方法调用时,消息没有发布。当我调试时,我看到电话挂在 两种方法中的代码都是 100% 相同的

List<String> messageIds = ApiFutures.allAsList(futures).get();

如何使用非主方法发布消息。 下面是我的代码。

@Slf4j
public class GCPMessagePublisher 

    private static final String PROJECT_ID = "myProjId";
    public static void main(String[] args) throws Exception
    
     
       String topicId = "testTopic";
        int messageCount = 10;
        String message="Hello GCP";
        ProjectTopicName topicName = ProjectTopicName.of(PROJECT_ID, topicId);

        List<ApiFuture<String>> futures = new ArrayList<>();
        Publisher publisher=null;

        try 
            GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("GCP Credential Here........"));

            publisher = Publisher.newBuilder(topicName).setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build();


                // convert message to bytes
                ByteString data = ByteString.copyFromUtf8(message);
                PubsubMessage pubsubMessage = PubsubMessage.newBuilder()
                        .setData(data)
                        .build();

                // Schedule a message to be published. Messages are automatically batched.
                ApiFuture<String> future = publisher.publish(pubsubMessage);
                futures.add(future);

         finally 
            // Wait on any pending requests
            List<String> messageIds = ApiFutures.allAsList(futures).get();

            for (String messageId : messageIds) 
                System.out.println("messageId Printing is "+messageId);
            

            if (publisher != null) 
                // When finished with the partypublisher, shutdown to free up resources.
                publisher.shutdown();
            
        
    
    public static void putMessageOnGCP(String Message) throws Exception
    

        //log.info("The outgoing message to GCP PUBSUB is : "+message);
 
        String topicId = "testTopic";
        String message="Hi GCP";
        ProjectTopicName topicName = ProjectTopicName.of(PROJECT_ID, topicId);

        List<ApiFuture<String>> futures = new ArrayList<>();
        Publisher publisher=null;

        try 
            GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("GCP Credential Here.........."));

            publisher = Publisher.newBuilder(topicName).setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build();

                // convert message to bytes
                ByteString data = ByteString.copyFromUtf8(message);
                PubsubMessage pubsubMessage = PubsubMessage.newBuilder()
                        .setData(data)
                        .build();

                // Schedule a message to be published. Messages are automatically batched.
                ApiFuture<String> future = publisher.publish(pubsubMessage);
                futures.add(future);

        catch (Exception e)
        

        
        finally 
            // Wait on any pending requests
            List<String> messageIds = ApiFutures.allAsList(futures).get();

            for (String messageId : messageIds) 
                System.out.println(messageId);
            

            if (publisher != null) 
                // When finished with the partypublisher, shutdown to free up resources.
                publisher.shutdown();
            
        
    


当我从其他方法调用时,我收到以下错误。当我检查谷歌凭据时,我可以看到它正在从谷歌凭据 JSON 文件中读取内容。

Caused by: com.google.api.gax.rpc.UnavailableException: io.grpc.StatusRuntimeException: UNAVAILABLE: io exception
Channel Pipeline: [SslHandler#0, ProtocolNegotiators$ClientTlsHandler#0, WriteBufferingAndExceptionHandler#0, DefaultChannelPipeline$TailContext#0]
    at com.google.api.gax.rpc.ApiExceptionFactory.createException(ApiExceptionFactory.java:69)
    at com.google.api.gax.grpc.GrpcApiExceptionFactory.create(GrpcApiExceptionFactory.java:72)
    at com.google.api.gax.grpc.GrpcApiExceptionFactory.create(GrpcApiExceptionFactory.java:60)
    at com.google.api.gax.grpc.GrpcExceptionCallable$ExceptionTransformingFuture.onFailure(GrpcExceptionCallable.java:97)
    at com.google.api.core.ApiFutures$1.onFailure(ApiFutures.java:68)
    at com.google.common.util.concurrent.Futures$CallbackListener.run(Futures.java:1039)
    at com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:30)
    at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1165)
    at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:958)
    at com.google.common.util.concurrent.AbstractFuture.setException(AbstractFuture.java:749)
    at io.grpc.stub.ClientCalls$GrpcFuture.setException(ClientCalls.java:522)
    at io.grpc.stub.ClientCalls$UnaryStreamToFuture.onClose(ClientCalls.java:497)
    at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:426)
    at io.grpc.internal.ClientCallImpl.access$500(ClientCallImpl.java:66)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.close(ClientCallImpl.java:689)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.access$900(ClientCallImpl.java:577)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:751)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:740)
    at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
    at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    ... 1 more
Caused by: io.grpc.StatusRuntimeException: UNAVAILABLE: io exception
Channel Pipeline: [SslHandler#0, ProtocolNegotiators$ClientTlsHandler#0, WriteBufferingAndExceptionHandler#0, DefaultChannelPipeline$TailContext#0]
    at io.grpc.Status.asRuntimeException(Status.java:533)
    ... 16 more
Caused by: javax.net.ssl.SSLHandshakeException: General OpenSslEngine problem
    at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslEngine.handshakeException(ReferenceCountedOpenSslEngine.java:1728)
    at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslEngine.wrap(ReferenceCountedOpenSslEngine.java:770)
    at java.base/javax.net.ssl.SSLEngine.wrap(SSLEngine.java:519)
    at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler.wrap(SslHandler.java:1043)
    at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler.wrapNonAppData(SslHandler.java:934)
    at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1392)
    at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1224)
    at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1271)
    at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:505)
    at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:444)
    at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:283)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352)
    at io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1422)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374)
    at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360)
    at io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:931)
    at io.grpc.netty.shaded.io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163)
    at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:700)
    at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:635)
    at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:552)
    at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:514)
    at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$6.run(SingleThreadEventExecutor.java:1044)
    at io.grpc.netty.shaded.io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.grpc.netty.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    ... 1 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
    at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:290)
    at java.base/sun.security.validator.Validator.validate(Validator.java:264)
    at java.base/sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:313)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:276)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:141)
    at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslClientContext$ExtendedTrustManagerVerifyCallback.verify(ReferenceCountedOpenSslClientContext.java:248)
    at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslContext$AbstractCertificateVerifier.verify(ReferenceCountedOpenSslContext.java:699)
    at io.grpc.netty.shaded.io.netty.internal.tcnative.SSL.readFromSSL(Native Method)
    at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslEngine.readPlaintextData(ReferenceCountedOpenSslEngine.java:589)
    at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1172)
    at io.grpc.netty.shaded.io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1289)
    at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler$SslEngineType$1.unwrap(SslHandler.java:199)
    at io.grpc.netty.shaded.io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1329)
    ... 21 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at java.base/sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
    at java.base/sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
    at java.base/java.security.cert.CertPathBuilder.build(CertPathBuilder.java:297)
    at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
    ... 34 more

我是否必须添加任何东西才能使其正常工作

【问题讨论】:

【参考方案1】:

最后我自己找到了答案。发生这种情况是因为我的个人信任库与 GCP 搞砸了。所以解决方案是

    转到谷歌云发布主题https://console.cloud.google.com/

    导入 GlobalSignCert

    将证书添加到您的信任库中

注意:如果您为您的应用使用不同的信任库,请按照上述步骤操作。 CACERTS 默认支持这个。

【讨论】:

【参考方案2】:

我们遇到了类似的问题,但这是因为我们使用了公司代理,并且在 JDK 的密钥库中没有我们的证书。 所以如果你在代理后面运行,你可能需要做同样的事情。 要遵循的步骤(假设您在 Windows 上):

    获取您的证书副本。我想我们是从 Windows 证书管理器中提取它的。它应该是 .crt 或 .pem 文件。 从管理员 powershell 或 cmd 提示符运行以下命令

keytool -import -alias &lt;alias-here&gt; -keystore "C:\Program Files\Java\&lt;jdk-version&gt;\jre\lib\security\cacerts" -file "&lt;\file\from\step\1.pem&gt;"

    它应该会提示输入密码,如果您之前没有更改过密码,只需“更改它”(也许考虑更改它!)

现在您应该能够重新启动您的 IDE 或重新编译您的代码,它不应该再给您 SunCertPath 异常了。

【讨论】:

你从谷歌网站谈论谷歌云证书是什么证书? 不,这将是代理的根 SSL 证书。如果您在 Windows 中转到“管理计算机证书”,然后打开“受信任的根证书颁发机构”,然后打开“证书”,应该会有您公司颁发的证书。如果您将其导出到 .cer 或 .pem 文件,您将使用帖子中的命令将其添加到 java 密钥库中。

以上是关于GCP-PUBSUB:-sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径的主要内容,如果未能解决你的问题,请参考以下文章

升级Java后无法找到Sun.security

未找到sun.security.ssl.SSLSessionImpl

异常解决:sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.cer

sun.security.validator.ValidatorException:PKIX 路径构建失败

sun.security.pkcs11.SunPKCS11的访问限制

Java NoSuchAlgorithmException - SunJSSE、sun.security.ssl.SSLContextImpl$DefaultSSLContext