“PKIX path building failed” and “unable to find va

2018-12-31 06:11发布

I'm trying to get tweets using twitter4j library for my java project. On my first run I got an error about certificate sun.security.validator.ValidatorException and sun.security.provider.certpath.SunCertPathBuilderException. Then I added twitter certificate by:

C:\Program Files\Java\jdk1.7.0_45\jre\lib\security>keytool -importcert -trustcacerts -file PathToCert -alias ca_alias -keystore "C:\Program Files\Java\jdk1.7.0_45\jre\lib\security\cacerts"

But without success. Here is the procedure to get twitters:

public static void main(String[] args) throws TwitterException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
        .setOAuthConsumerKey("myConsumerKey")
        .setOAuthConsumerSecret("myConsumerSecret")
        .setOAuthAccessToken("myAccessToken")
        .setOAuthAccessTokenSecret("myAccessTokenSecret");

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    try {
        Query query = new Query("iphone");
        QueryResult result;
        result = twitter.search(query);
        System.out.println("Total amount of tweets: " + result.getTweets().size());
        List<Status> tweets = result.getTweets();

        for (Status tweet : tweets) {
            System.out.println("@" + tweet.getUser().getScreenName() + " : " + tweet.getText());
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
    }

And here is the error:

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Relevant discussions can be found on the Internet at:
    http://www.google.co.jp/search?q=d35baff5 or
    http://www.google.co.jp/search?q=1446302e
TwitterException{exceptionCode=[d35baff5-1446302e 43208640-747fd158 43208640-747fd158 43208640-747fd158], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.5}
    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:177)
    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
    at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:81)
    at twitter4j.TwitterImpl.get(TwitterImpl.java:1929)
    at twitter4j.TwitterImpl.search(TwitterImpl.java:306)
    at jku.cc.servlets.TweetsAnalyzer.main(TweetsAnalyzer.java:38)
Caused by: 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(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
    at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
    at sun.security.ssl.Handshaker.processLoop(Unknown Source)
    at sun.security.ssl.Handshaker.process_record(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
    at twitter4j.internal.http.HttpResponseImpl.<init>(HttpResponseImpl.java:34)
    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:141)
    ... 5 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 sun.security.validator.PKIXValidator.doBuild(Unknown Source)
    at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
    at sun.security.validator.Validator.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    ... 20 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    ... 26 more
Failed to search tweets: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

22条回答
余生请多指教
2楼-- · 2018-12-31 06:37

I had a slightly different situation, when both JDK and JRE 1.8.0_112 were present on my system.

I imported the new CA certificates into [JDK_FOLDER]\jre\lib\security\cacerts using the already known command:

keytool -import -trustcacerts -keystore cacerts -alias <new_ca_alias> -file <path_to_ca_cert_file>

Still, I kept getting the same PKIX path building failed error.

I added debug information to the java CLI, by using java -Djavax.net.debug=all ... > debug.log. In the debug.log file, the line that begins with trustStore is: actually pointed to the cacerts store found in [JRE_FOLDER]\lib\security\cacerts.

In my case the solution was to copy the cacerts file used by JDK (which had the new CAs added) over the one used by the JRE and that fixed the issue.

查看更多
十年一品温如言
3楼-- · 2018-12-31 06:37

This isn't a Twitter-specific answer, but this is the question that comes up when you search for this error. If your system is receiving this error when connecting to a website that appears to have a valid certificate when viewed in a web browser, that probably means that website has an incomplete certificate chain.

For a brief summary of the problem: Certificate Authorities don't use their Root Certificate to sign just any old certificate. Instead, they (usually) sign intermediate certificates that also have the Certificate Authority flag set (that is, are allowed to sign certificates). Then when you purchase a certificate from a CA, they sign your CSR with one of these intermediate certificates.

Your Java trust store most likely only has the Root Cert, not the intermediate ones.

A misconfigured site might return just their signed cert. Problem: it was signed with an intermediate cert that's not in your trust store. Browsers will handle this problem by downloading or using a cached intermediate certificate; this maximizes website compatibility. Java and tools like OpenSSL, however, won't. And that will cause the error in the question.

You can verify this suspicion by using the Qualys SSL Test. If you run that against a site and it says

This server's certificate chain is incomplete.

then that confirms it. You can also see this by looking at the certification paths and seeing the text Extra Download.

How to fix it: the server administrator needs to configure the web server to return the intermediate certificates as well. For Comodo, for example, this is where the .ca-bundle file comes in handy. For example, in an Apache configuration with mod_ssl, you'd use the SSLCertificateChainFile configuration setting. For nginx, you need to concatenate the intermediate certificates and the signed certificate and use that in the SSL cert configuration. You can find more by searching for "incomplete certificate chain" online.

查看更多
泪湿衣
4楼-- · 2018-12-31 06:38

1. Check the certificate

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. It's on the left or right side of the browser's address bar) whether it's expired or untrusted by other reason.

2. Install latest versions of JRE and JDK

New versions usually come with the updated set of the trusted certificates.

Also if it's possible, uninstall old versions. This will make misconfiguration errors explicit.

3. Check your configuration:

  • Check where your JAVA_HOME environment variable points to.
  • Check which java version you use to run the program. In IntelliJ check:
    • File -> Project Structure... -> Project Settings -> Project -> Project SDK:
    • File -> Project Structure... -> Platform Settings -> SDKs

4. Copy whole keystore from the new Java version

If you develop under the JDK other than the latest available - try to replace the %JAVA_HOME%/jre/lib/security/cacerts file with the new one from the latest installed JRE (make a backup copy first) as @jeremy-goodell suggests in his answer

5. Add certificate(s) to your keystore

If nothing above solves your problem use keytool to save certificate(s) to the Java's keystore:

keytool -trustcacerts -keystore "%JAVA_HOME%jre\lib\security\cacerts" -storepass changeit -importcert -alias <alias_name> -file <path_to_crt_file>

File with the certificate can be obtained from the browser as @MagGGG suggests in his answer.

Note 1: you may need to repeat this for every certificate in the chain to you site's certificate. Start from the root one.

Note 2: <alias_name> should be unique among the keys in the store or keytool will show an error.

To get list of all the certificates in the store you may run:

keytool -list -trustcacerts -keystore "%JAVA_HOME%jre\lib\security\cacerts" -storepass changeit

In case something goes wrong this will help you to remove certificate from the store:

keytool -delete -alias <alias_name> -keystore "%JAVA_HOME%jre\lib\security\cacerts" -storepass changeit
查看更多
泛滥B
5楼-- · 2018-12-31 06:41
-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true

It is used for jump the certificate validation.

查看更多
何处买醉
6楼-- · 2018-12-31 06:41

When you have above error with atlassian software ex. jira

2018-08-18 11:35:00,312 Caesium-1-4 WARN anonymous    Default Mail Handler [c.a.mail.incoming.mailfetcherservice] Default Mail Handler[10001]: javax.mail.MessagingException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target while connecting to host 'imap.xyz.pl' as user 'jira@xyz.pl' via protocol 'imaps, caused by: 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

you can add certs to it's trusted keystore (change missing_ca to proper cert name):

keytool -importcert -file missing_ca.crt -alias missing_ca -keystore /opt/atlassian/jira/jre/lib/security/cacerts

If asked for password put changeit and confirm y

After that simply restart jira.

查看更多
牵手、夕阳
7楼-- · 2018-12-31 06:42

i have the same problem on ubuntu 15.10. Please try download plugin locally e.g. https://github.com/lmenezes/elasticsearch-kopf/archive/master.zip and install with this command:

sudo /usr/share/elasticsearch/bin/plugin install file:/home/dev/Downloads/elasticsearch-kopf-master.zip

Path maybe different depending on your environment.

Regards.

查看更多
登录 后发表回答