question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

java.io.IOException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

See original GitHub issue

**The situation is the same as described on 25 April 2019 (https://github.com/pengrad/java-telegram-bot-api/issues/160#issue-437322657). The difference is that we changed the server, a new installation. But from what I understood at the time, what made it work was the custom OkHttpClient. Here is the implementation of the class:

Remembering that this error only happens when my application is on the server, which uses https**

`public class BuilderCustomTelegram {

private final String token;

public BuilderCustomTelegram(String token) { this.token = token; }

public TelegramBot getTelegramBot() { X509TrustManager trustManager; SSLSocketFactory sslSocketFactory;

try {
    trustManager = trustManagerForCertificates(trustedCertificatesInputStream());
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[]{trustManager}, null);
    sslSocketFactory = sslContext.getSocketFactory();
} catch (GeneralSecurityException e) {
    throw new RuntimeException(e);
}

OkHttpClient client = new OkHttpClient.Builder()
        .sslSocketFactory(sslSocketFactory, trustManager)
        .build();

TelegramBot bot = new TelegramBot.Builder(token)
        .okHttpClient(client)
        .build();

return bot;

}

private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream in = null; // By convention, ‘null’ creates an empty key store. keyStore.load(in, password); return keyStore; } catch (IOException e) { throw new AssertionError(e); } }

private X509TrustManager trustManagerForCertificates(InputStream in) throws GeneralSecurityException { CertificateFactory certificateFactory = CertificateFactory.getInstance(“X.509”); Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in); if (certificates.isEmpty()) { throw new IllegalArgumentException(“expected non-empty set of trusted certificates”); }

// Put the certificates a key store.
char[] password = "password".toCharArray(); // Any password will work.
KeyStore keyStore = newEmptyKeyStore(password);
int index = 0;
for (Certificate certificate : certificates) {
    String certificateAlias = Integer.toString(index++);
    keyStore.setCertificateEntry(certificateAlias, certificate);
}

// Use it to build an X509 trust manager.
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);

TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
return (X509TrustManager) trustManagers[0];

}

private InputStream trustedCertificatesInputStream() { // PEM files for root certificates of Comodo and Entrust. These two CAs are sufficient to view // https://publicobject.com (Comodo) and https://squareup.com (Entrust). But they aren’t // sufficient to connect to most HTTPS sites including https://godaddy.com and https://visa.com. // Typically developers will need to get a PEM file from their organization’s TLS administrator. String comodoRsaCertificationAuthority = “” + “-----BEGIN CERTIFICATE-----\n” + “MIIEiDCCA3CgAwIBAgIQIZasKdlbfwsnz6AiPh7PVDANBgkqhkiG9w0BAQsFADBI\n” + “MRswGQYDVQQDExJFU0VUIFNTTCBGaWx0ZXIgQ0ExHDAaBgNVBAoTE0VTRVQsIHNw\n” + “b2wuIHMgci4gby4xCzAJBgNVBAYTAlNLMB4XDTIwMDEyMjAwMDAwMFoXDTIyMDQy\n” + “MTIzNTk1OVowggEbMRUwEwYDVQQFEwxMMDcwMDAxMTMzMjExEzARBgsrBgEEAYI3\n” + “PAIBAxMCVVMxGDAWBgsrBgEEAYI3PAIBAhMHRmxvcmlkYTEdMBsGA1UEDxMUUHJp\n” + “dmF0ZSBPcmdhbml6YXRpb24xCzAJBgNVBAYTAlVTMQ4wDAYDVQQREwUzMzcwMTEQ\n” + “MA4GA1UECBMHRmxvcmlkYTEZMBcGA1UEBxMQU0FJTlQgUEVURVJTQlVSRzEnMCUG\n” + “A1UECRMeMTQ2IFNFQ09ORCBTVFJFRVQgTi4gU1VJVEUgMjAxMSAwHgYDVQQKExdS\n” + “YXBpZCBXZWIgU2VydmljZXMsIExMQzEfMB0GA1UEAxMWd3d3LmNvbW9kb3NzbHN0\n” + “b3JlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKLf1o/6IKeh\n” + “MDUIs/mk8F5Vb5MUun1DNfNcob/gXQ006gvfBYgb/HB9V6GxXp9Y0o9W+uuO3X9T\n” + “QJmfSytppTIcT5sMfr+BatZXJIb6083PlHEw4e2/2kGgC3AeYs401GYYKWSUlygm\n” + “1VwZIYnWmp5evJvpbox5cZ0ASwdOjiduVN/Qm62IqcXB8K4ekDb2VK0L6zirRjTE\n” + “mpbrHyuECYhNH3Uzaz/swnVfa8CRkS2UvUiXiXSazz5qtbf5lXSNi/tyrmMQr3Oj\n” + “Pz3/AyTo+hvGSTia4iPje3B4EUJ8D3eLMuSsTjizAHx+1bWXpYymRgb6kMtzQc6C\n” + “2ZFw488Ko40CAwEAAaOBmDCBlTAMBgNVHRMBAf8EAjAAMB0GA1UdJQQWMBQGCCsG\n” + “AQUFBwMBBggrBgEFBQcDAjA1BgNVHREELjAsghZ3d3cuY29tb2Rvc3Nsc3RvcmUu\n” + “Y29tghJjb21vZG9zc2xzdG9yZS5jb20wDgYDVR0PAQH/BAQDAgWgMB8GA1UdIwQY\n” + “MBaAFHOMID6LT/zrhQQxbbv3834Lbv6bMA0GCSqGSIb3DQEBCwUAA4IBAQBeI3df\n” + “uBRjce9g3ng8fLNi6hw+D+W5Fof0h4jEbrXzTSMcJxEylK0JrWOsyV9CvKZjzghG\n” + “18gE+6dr7pLfMNbHYjJ1ZT9U/zD55xUrbt4CeB5U3sL/KfryYQ/yekT9YBoK9MeQ\n” + “0G2fRYEhWIwHxeulJPPeyPSF52iJRp/234ccrjGDS7Qt7Jrdf2anO+0CcuoxS9Oz\n” + “/fJEkjlCIenqeoffbkiXxvv72If0YmRpvDS7OPiOR1CStLo2E3D7h/Bzu4p+CS4f\n” + “t2ZUsB3PTwM/j0FvWI7UV27f2mpqRlMebS4v+sgR174LMVzp3R7VM/VJWPsY3wwL\n” + “S3wGpBrU4o4sAdtU\n” + “-----END CERTIFICATE-----”;

return new Buffer()
        .writeUtf8(comodoRsaCertificationAuthority)
        .inputStream();

} } `

And this is the error:

java.lang.RuntimeException: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at com.pengrad.telegrambot.impl.TelegramBotClient.send(TelegramBotClient.java:67) at com.pengrad.telegrambot.TelegramBot.execute(TelegramBot.java:42) at br.com.portal.web.view.administracao.telegram.teste.TelegramTesteView.enviarPeloTelegramBot(TelegramTesteView.java:123) at br.com.portal.web.view.administracao.telegram.teste.TelegramTesteView.enviar(TelegramTesteView.java:68) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at com.sun.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:153) at com.sun.el.parser.AstValue.invoke(AstValue.java:261) at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:237) at org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40) at org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50) at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:65) at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:124) at javax.faces.event.ActionEvent.processListener(ActionEvent.java:72) at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:490) at javax.faces.component.UICommand.broadcast(UICommand.java:211) at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:847) at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1396) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:58) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:177) at javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:707) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:451) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1636) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:331) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211) at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:81) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:253) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211) at br.com.portal.web.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:33) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:253) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211) at br.com.sigmax.web.servlet.HSTSFilter.doFilter(HSTSFilter.java:31) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:253) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211) at br.com.sigmax.web.servlet.SecurityFilter.doFilter(SecurityFilter.java:69) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:253) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:211) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:257) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:757) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:577) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:158) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238) at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:524) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549) at java.base/java.lang.Thread.run(Thread.java:834) Caused by: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131) at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:321) at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:264) at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:259) at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.checkServerCerts(CertificateMessage.java:1337) at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.onConsumeCertificate(CertificateMessage.java:1212) at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.consume(CertificateMessage.java:1155) at java.base/sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:392) at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:450) at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:427) at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:178) at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:164) at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1151) at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1062) at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:402) at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:320) at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:284) at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:169) at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:258) at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135) at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114) at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:127) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:257) at okhttp3.RealCall.execute(RealCall.java:93) at com.pengrad.telegrambot.impl.TelegramBotClient.send(TelegramBotClient.java:64) … 66 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:439) at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:306) 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:222) at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:129) at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.checkServerCerts(CertificateMessage.java:1321) … 96 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:434) … 102 more

Issue Analytics

  • State:open
  • Created 3 years ago
  • Comments:20 (9 by maintainers)

github_iconTop GitHub Comments

1reaction
vitalystercommented, Jun 26, 2020

@roabol there is no need to use oracle jdk11 distribution under centos, that is the reason you have broken ca certificates authority. Just switch to openjdk-devel centos jdk package and it will pick correct ca certificates automatically.

0reactions
Abu-Abdullahcommented, Jul 14, 2022

ok solved by the same above workaround having custom OkHttpClient, for some reason it didnt work when i tried to import directly in keystore /etc/ssl/certs/java/cacerts

this is how i got it:

openssl s_client -connect api.telegram.org:443 -tls1_3

i still do hope that such thing is implemented internally without any need for such workaround

Read more comments on GitHub >

github_iconTop Results From Across the Web

java - "PKIX path building failed" and "unable to find valid ...
Try to load the target URL in browser and view the site's certificate (usually it's accessible by the icon with the lock sign....
Read more >
Unable to connect to SSL services due to "PKIX Path Building ...
SunCertPathBuilderException : unable to find valid certification path to requested target at sun.security.validator.PKIXValidator.
Read more >
Solve “pkix path building failed” - Packagecloud Blog
In the simplest of terms, the error occurs when the Java framework fails to validate the SSL certificate of the URL that is...
Read more >
How to resolve PKIX path building failed/unable to find valid ...
Reason: The error due to the system firewall. · Solution: The solution is very simple. · To download the certificate, follow the below...
Read more >
PKIX path building failed error message
The most common reason for this issue is the certificate is provided by an internal Root CA or is a Self-Signed Certificate. This...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found