[java] Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

Edit :- Tried to format the question and accepted answer in more presentable way at mine Blog

Here is the original issue.

I am getting this error:

detailed message sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

cause 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

I am using Tomcat 6 as webserver. I have two HTTPS web applications installed on different Tomcats on different ports but on the same machine. Say App1(port 8443) and App2(port 443). App1 connects to App2. When App1 connects to App2 I get the above error. I know this is a very common error so came across many solutions on different forums and sites. I have the below entry in server.xml of both Tomcats:

keystoreFile="c:/.keystore" 
keystorePass="changeit"

Every site says the same reason that certificate given by app2 is not in the trusted store of app1 jvm. This seems to be true also when I tried to hit the same URL in IE browser, it works (with warming, There is a problem with this web site's security certificate. Here I say continue to this website). But when same URL is hit by Java client (in my case) I get the above error. So to put it in the truststore I tried these three options:

Option1

System.setProperty("javax.net.ssl.trustStore", "C:/.keystore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

Option2 Setting below in environment variable

CATALINA_OPTS -- param name
-Djavax.net.ssl.trustStore=C:\.keystore -Djavax.net.ssl.trustStorePassword=changeit ---param value

Option3 Setting below in environment variable

JAVA_OPTS -- param name
-Djavax.net.ssl.trustStore=C:\.keystore -Djavax.net.ssl.trustStorePassword=changeit ---param value

But nothing worked .

What at last worked is executing the Java approach suggested in How to handle invalid SSL certificates with Apache HttpClient? by Pascal Thivent i.e. executing the program InstallCert.

But this approach is fine for devbox setup but I can not use it at production environment.

I am wondering why three approaches mentioned above did not work when I have mentioned the same values in server.xml of app2 server and same values in truststore by setting

System.setProperty("javax.net.ssl.trustStore", "C:/.keystore") and System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

in app1 program.

For more information this is how I am making the connection:

URL url = new URL(urlStr);

URLConnection conn = url.openConnection();

if (conn instanceof HttpsURLConnection) {

  HttpsURLConnection conn1 = (HttpsURLConnection) url.openConnection();

  conn1.setHostnameVerifier(new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
      return true;
    }
  });

  reply.load(conn1.getInputStream());

This question is related to java ssl https

The answer is


I have this problem too.

I tried almost everything by adding the SSL cert to .keystore, but, it was not working with Java1_6_x. For me it helped if we start using newer version of Java, Java1_8_x as JVM.


I was using jdk1.8.0_171 when I faced the same issue. I tried top 2 solutions here (adding a certificate using keytool and another solution which has a hack in it) but they didn't work for me.

I upgraded my JDK to 1.8.0_181 and it worked like a charm.


I want to chime in since I have a QEMU environment where I have to download files in java. It turns out the /etc/ssl/certs/java/cacerts in QEMU does have problem because it does not match the /etc/ssl/certs/java/cacerts in the host environment. The host environment is behind a company proxy so the java cacerts is a customized version.

If you are using a QEMU environment, make sure the host system can access files first. For example you can try this script on your host machine first to see. If the script runs just fine in host machine but not in QEMU, then you are having the same problem as me.

To solve this issue, I had to make a backup of the original file in QEMU, copy over the file in host environment to the QEMU chroot jail, and then java could download files normally in QEMU.

A better solution would be mount the /etc into the QEMU environment; however I am not sure if other files will get impacted in this process. So I decided to use this ugly but easy work-around.


for safety we should not use self signed certificates in our implementation. However, when it comes to development often we have to use trial environments which got self-signed certs. I tried to fix this issue programmatically in my code and I fail. However, by adding the cert to the jre trust-store fixed my issue. Please find below steps,

  1. Download the site cert,

  2. Copy the certificate(ex:cert_file.cer) into the directory $JAVA_HOME\Jre\Lib\Security

  3. Open CMD in Administrator and change the directory to $JAVA_HOME\Jre\Lib\Security

  4. Import the certificate to a trust store using below command,

keytool -import -alias ca -file cert_file.cer -keystore cacerts -storepass changeit

If you got a error saying keytool is not recognizable please refer this.

Type yes like below

Trust this certificate: [Yes]

  1. Now try to run your code or access the URL programmatically using java.

Update

If your app server is jboss try adding below system property

System.setProperty("org.jboss.security.ignoreHttpsHost","true");

Hope this helps!


In a pinch, you can disable SSL entirely, or per connection (note this is not recommended for production!) see https://stackoverflow.com/a/19542614/32453


Another reason could be an outdated version of JDK. I was using jdk version 1.8.0_60, simply updating to the latest version solved the certificate issue.


My cacerts file was totally empty. I solved this by copying the cacerts file off my windows machine (that's using Oracle Java 7) and scp'd it to my Linux box (OpenJDK).

cd %JAVA_HOME%/jre/lib/security/
scp cacerts mylinuxmachin:/tmp

and then on the linux machine

cp /tmp/cacerts /etc/ssl/certs/java/cacerts

It's worked great so far.


Just a small hack. Update the URL in the file "hudson.model.UpdateCenter.xml" from https to http

<?xml version='1.1' encoding='UTF-8'?>
<sites>
  <site>
    <id>default</id>
    <url>http://updates.jenkins.io/update-center.json</url>
  </site>
</sites>

i wrote a small win32 (WinXP 32bit testet) stupid cmd (commandline) script which looks for all java versions in program files and adds a cert to them. The Password needs to be the default "changeit" or change it yourself in the script :-)

@echo off

for /F  %%d in ('dir /B %ProgramFiles%\java') do (
    %ProgramFiles%\Java\%%d\bin\keytool.exe -import -noprompt -trustcacerts -file some-exported-cert-saved-as.crt -keystore %ProgramFiles%\Java\%%d\lib\security\cacerts -storepass changeit
)

pause

This seems as good a place as any to document another possible reason for the infamous PKIX error message. After spending far too long looking at the keystore and truststore contents and various java installation configs I realised that my issue was down to... a typo.

The typo meant that I was also using the keystore as the truststore. As my companies Root CA was not defined as a standalone cert in the keystore but only as part of a cert chain, and was not defined anywhere else (i.e. cacerts) I kept getting the PKIX error.

After a failed release (this is prod config, it was ok elsewhere) and two days of head scratching I finally saw the typo, and now all is good.

Hope this helps someone.


For me didn't work the recognized solution from this post: https://stackoverflow.com/a/9619478/4507034.

Instead, I managed to solve the problem by importing the certification to my machine trusted certifications.

Steps:

  1. Go to the URL (eg. https://localhost:8443/yourpath) where the certification is not working.
  2. Export the certification as described in the mentioned post.
  3. On your windows machine open: Manage computer certificates
  4. Go to Trusted Root Certification Authorities -> Certificates
  5. Import here your your_certification_name.cer file.

My two cents: In my case, cacerts was not a folder, but a file, and also it was presents on two paths After discover it, error disappeared after copy the .jks file over that file.

# locate cacerts    
/usr/java/jdk1.8.0_221-amd64/jre/lib/security/cacerts
/usr/java/jre1.8.0_221-amd64/lib/security/cacerts

After backup them, I copy the .jks over.

cp /path_of_jks_file/file.jks /usr/java/jdk1.8.0_221-amd64/jre/lib/security/cacerts
cp /path_of_jks_file/file.jks /usr/java/jre1.8.0_221-amd64/lib/security/cacerts

Note: this basic trick resolves this error on a Genexus project, in spite file.jks is also on the server.xml file of the Tomcat.


For me, this error appeared too while trying to connect to a process behind an NGINX reverse proxy which was handling the SSL.

It turned out the problem was a certificate without the entire certificate chain concatenated. When I added intermediate certs, the problem was solved.

Hope this helps.


I ran into this issue while making REST calls from my app server running in AWS EC2. The following Steps fixed the issue for me.

  1. curl -vs https://your_rest_path
  2. echo | openssl s_client -connect your_domain:443
  3. sudo apt-get install ca-certificates

curl -vs https://your_rest_path will now work!


In my case the issue was that the webserver was only sending the certificate and the intermediate CA, not the root CA. Adding this JVM option solved the problem: -Dcom.sun.security.enableAIAcaIssuers=true

Support for the caIssuers access method of the Authority Information Access extension is available. It is disabled by default for compatibility and can be enabled by setting the system property com.sun.security.enableAIAcaIssuers to the value true.

If set to true, Sun's PKIX implementation of CertPathBuilder uses the information in a certificate's AIA extension (in addition to CertStores that are specified) to find the issuing CA certificate, provided it is a URI of type ldap, http, or ftp.

Source


I was having this problem with Android Studio when I'm behind a proxy. I was using Crashlytics that tries to upload the mapping file during a build.

I added the missing proxy certificate to the truststore located at /Users/[username]/Documents/Android Studio.app/Contents/jre/jdk/Contents/Home/jre/lib/security/cacerts

with the following command: keytool -import -trustcacerts -keystore cacerts -storepass [password] -noprompt -alias [alias] -file [my_certificate_location]

for example with the default truststore password keytool -import -trustcacerts -keystore cacerts -storepass changeit -noprompt -alias myproxycert -file /Users/myname/Downloads/MyProxy.crt


How to work-it in Tomcat 7

I wanted to support a self signed certificate in a Tomcat App but the following snippet failed to work

import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HTTPSPlayground {
    public static void main(String[] args) throws Exception {

        URL url = new URL("https:// ... .com");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        httpURLConnection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());

        String serializedMessage = "{}";
        wr.writeBytes(serializedMessage);
        wr.flush();
        wr.close();

        int responseCode = httpURLConnection.getResponseCode();
        System.out.println(responseCode);
    }
}

this is what solved my issue:

1) Download the .crt file

echo -n | openssl s_client -connect <your domain>:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/<your domain>.crt
  • replace <your domain> with your domain (e.g. jossef.com)

2) Apply the .crt file in Java's cacerts certificate store

keytool -import -v -trustcacerts -alias <your domain> -file ~/<your domain>.crt -keystore <JAVA HOME>/jre/lib/security/cacerts -keypass changeit -storepass changeit
  • replace <your domain> with your domain (e.g. jossef.com)
  • replace <JAVA HOME> with your java home directory

3) Hack it

Even though iv'e installed my certificate in Java's default certificate stores, Tomcat ignores that (seems like it's not configured to use Java's default certificate stores).

To hack this, add the following somewhere in your code:

String certificatesTrustStorePath = "<JAVA HOME>/jre/lib/security/cacerts";
System.setProperty("javax.net.ssl.trustStore", certificatesTrustStorePath);

// ...

  • Make sure of your JVM location. There can be half a dozen JREs on your system. Which one is your Tomcat really using? Anywhere inside code running in your Tomcat, write println(System.getProperty("java.home")). Note this location. In <java.home>/lib/security/cacerts file are the certificates used by your Tomcat.
  • Find the root certificate that is failing. This can be found by turning on SSL debug using -Djavax.net.debug=all. Run your app and note from console ssl logs the CA that is failing. Its url will be available. In my case I was surprised to find that a proxy zscaler was the one which was failing, as it was actually proxying my calls, and returning its own CA certificate.
  • Paste url in browser. Certificate will get downloaded.
  • Import this certificate into cacerts using keytool import.

Using Tomcat 7 under Linux, this did the trick.

String certificatesTrustStorePath = "/etc/alternatives/jre/lib/security/cacerts";
System.setProperty("javax.net.ssl.trustStore", certificatesTrustStorePath);
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

Under Linux, $JAVA_HOME is not always setup, but usually /etc/alternatives/jre points to $JAVA_HOME/jre


For MacOS X below is the exact command worked for me where I had to try with double hypen in 'importcert' option which worked :

sudo keytool -–importcert -file /PathTo/YourCertFileDownloadedFromBrowserLockIcon.crt -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home/jre/lib/security/cacerts -alias "Cert" -storepass changeit

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

• When I got the error, I tried to Google out the meaning of the expression and I found, this issue occurs when a server changes their HTTPS SSL certificate, and our older version of java doesn’t recognize the root certificate authority (CA).

• If you can access the HTTPS URL in your browser then it is possible to update Java to recognize the root CA.

• In your browser, go to the HTTPS URL that Java could not access. Click on the HTTPS certificate chain (there is lock icon in the Internet Explorer), click on the lock to view the certificate.

• Go to “Details” of the certificate and “Copy to file”. Copy it in Base64 (.cer) format. It will be saved on your Desktop.

• Install the certificate ignoring all the alerts.

• This is how I gathered the certificate information of the URL that I was trying to access.

Now I had to make my java version to know about the certificate so that further it doesn’t refuse to recognize the URL. In this respect I must mention that I googled out that root certificate information stays by default in JDK’s \jre\lib\security location, and the default password to access is: changeit.

To view the cacerts information the following are the procedures to follow:

• Click on Start Button-->Run

• Type cmd. The command prompt opens (you may need to open it as administrator).

• Go to your Java/jreX/bin directory

• Type the following

keytool -list -keystore D:\Java\jdk1.5.0_12\jre\lib\security\cacerts

It gives the list of the current certificates contained within the keystore. It looks something like this:

C:\Documents and Settings\NeelanjanaG>keytool -list -keystore D:\Java\jdk1.5.0_12\jre\lib\security\cacerts

Enter keystore password: changeit

Keystore type: jks

Keystore provider: SUN

Your keystore contains 44 entries

verisignclass3g2ca, Mar 26, 2004, trustedCertEntry,

Certificate fingerprint (MD5): A2:33:9B:4C:74:78:73:D4:6C:E7:C1:F3:8D:CB:5C:E9

entrustclientca, Jan 9, 2003, trustedCertEntry,

Certificate fingerprint (MD5): 0C:41:2F:13:5B:A0:54:F5:96:66:2D:7E:CD:0E:03:F4

thawtepersonalbasicca, Feb 13, 1999, trustedCertEntry,

Certificate fingerprint (MD5): E6:0B:D2:C9:CA:2D:88:DB:1A:71:0E:4B:78:EB:02:41

addtrustclass1ca, May 1, 2006, trustedCertEntry,

Certificate fingerprint (MD5): 1E:42:95:02:33:92:6B:B9:5F:C0:7F:DA:D6:B2:4B:FC

verisignclass2g3ca, Mar 26, 2004, trustedCertEntry,

Certificate fingerprint (MD5): F8:BE:C4:63:22:C9:A8:46:74:8B:B8:1D:1E:4A:2B:F6

• Now I had to include the previously installed certificate into the cacerts.

• For this the following is the procedure:

keytool –import –noprompt –trustcacerts –alias ALIASNAME -file FILENAME_OF_THE_INSTALLED_CERTIFICATE -keystore PATH_TO_CACERTS_FILE -storepass PASSWORD

If you are using Java 7:

keytool –importcert –trustcacerts –alias ALIASNAME -file PATH_TO_FILENAME_OF_THE_INSTALLED_CERTIFICATE -keystore PATH_TO_CACERTS_FILE -storepass changeit

• It will then add the certificate information into the cacert file.

It is the solution I found for the Exception mentioned above!!


For Tomcat running on Ubuntu server, to find out which Java is being used, use "ps -ef | grep tomcat" command:

Sample:

/home/mcp01$ **ps -ef |grep tomcat**
tomcat7  28477     1  0 10:59 ?        00:00:18 **/usr/local/java/jdk1.7.0_15/bin/java** -Djava.util.logging.config.file=/var/lib/tomcat7/conf/logging.properties -Djava.awt.headless=true -Xmx512m -XX:+UseConcMarkSweepGC -Djava.net.preferIPv4Stack=true -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.endorsed.dirs=/usr/share/tomcat7/endorsed -classpath /usr/share/tomcat7/bin/bootstrap.jar:/usr/share/tomcat7/bin/tomcat-juli.jar -Dcatalina.base=/var/lib/tomcat7 -Dcatalina.home=/usr/share/tomcat7 -Djava.io.tmpdir=/tmp/tomcat7-tomcat7-tmp org.apache.catalina.startup.Bootstrap start
1005     28567 28131  0 11:34 pts/1    00:00:00 grep --color=auto tomcat

Then, we can go in to: cd /usr/local/java/jdk1.7.0_15/jre/lib/security

Default cacerts file is located in here. Insert the untrusted certificate into it.


It is possible to disable SSL verification programmatically. Works in a pinch for dev, but not recommended for production since you'll want to either use "real" SSL verification there or install and use your own trusted keys and then still use "real" SSL verification.

Below code works for me:

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

public class TrustAnyTrustManager implements X509TrustManager {

  public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  }

  public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  }

  public X509Certificate[] getAcceptedIssuers() {
    return null;
  }
}

             HttpsURLConnection conn = null;
             URL url = new URL(serviceUrl);
             conn = (HttpsURLConnection) url.openConnection();
             SSLContext sc = SSLContext.getInstance("SSL");  
             sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());  
                    // Create all-trusting host name verifier
             HostnameVerifier allHostsValid = new HostnameVerifier() {
               public boolean verify(String hostname, SSLSession session) {
                return true;
              }
            };
            conn.setHostnameVerifier(allHostsValid);

Or if you don't control the Connections underneath, you can also override SSL verification globally for all connections https://stackoverflow.com/a/19542614/32453

If you are using Apache HTTPClient you must disable it "differently" (sadly): https://stackoverflow.com/a/2703233/32453


DEPLOYABLE SOLUTION (Alpine Linux)

To be able to fix this issue in our application environments, we have prepared Linux terminal commands as follows:

cd ~

Will generate cert file in home directory.

apk add openssl

This command installs openssl in alpine Linux. You can find proper commands for other Linux distributions.

openssl s_client -connect <host-dns-ssl-belongs> < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > public.crt

Generated the needed cert file.

sudo $JAVA_HOME/bin/keytool -import -alias server_name -keystore $JAVA_HOME/lib/security/cacerts -file public.crt -storepass changeit -noprompt

Applied the generated file to the JRE with the program 'keytool'.

Note: Please replace your DNS with <host-dns-ssl-belongs>

Note2: Please gently note that -noprompt will not prompt the verification message (yes/no) and -storepass changeit parameter will disable password prompt and provide the needed password (default is 'changeit'). These two properties will let you use those scripts in your application environments like building a Docker image.

Note3 If you are deploying your app via Docker, you can generate the secret file once and put it in your application project files. You won't need to generate it again and again.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to ssl

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website A fatal error occurred while creating a TLS client credential. The internal error state is 10013 curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number How to install OpenSSL in windows 10? ssl.SSLError: tlsv1 alert protocol version Invalid self signed SSL cert - "Subject Alternative Name Missing" "SSL certificate verify failed" using pip to install packages ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel "ssl module in Python is not available" when installing package with pip3

Examples related to https

What's the net::ERR_HTTP2_PROTOCOL_ERROR about? Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website Android 8: Cleartext HTTP traffic not permitted ssl.SSLError: tlsv1 alert protocol version Invalid self signed SSL cert - "Subject Alternative Name Missing" How do I make a https post in Node Js without any third party module? Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint How to force Laravel Project to use HTTPS for all routes? Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback Use .htaccess to redirect HTTP to HTTPs