ChatGPT解决这个技术问题 Extra ChatGPT

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

Edit : I tried to format the question and accepted answer in more presentable way at my 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:

Option 1

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

Option 2

Setting below in environment variable

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

Option 3

Setting below in environment variable

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

Result

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());
possible duplicate of HttpClient and SSL
Odly enough I got this error when communicating between clustered servers that had no SSL problems individually. Once I properly set domainname in my RHEL servers the problem was gone. Hope it helps someone.
One other thing to check is that you have the latest version of Java - I was getting a similar error because of this.
stackoverflow.com/questions/2893819/… - also relevant and a fantastic answer.
First of all import you'r crt file into {JAVA_HOME}/jre/security/cacerts, if you still faced with this exception, change you'r jdk version. For example from jdk1.8.0_17 to jdk1.8.0_231

S
SimonSez

You need to add the certificate for App2 to the truststore file of the used JVM located at $JAVA_HOME\lib\security\cacerts.

First you can check if your certificate is already in the truststore by running the following command: keytool -list -keystore "$JAVA_HOME/jre/lib/security/cacerts" (you don't need to provide a password)

If your certificate is missing, you can get it by downloading it with your browser and add it to the truststore with the following command:

keytool -import -noprompt -trustcacerts -alias <AliasName> -file   <certificate> -keystore <KeystoreFile> -storepass <Password>

Example:

keytool -import -noprompt -trustcacerts -alias myFancyAlias -file /path/to/my/cert/myCert.cer -keystore /path/to/my/jdk/jre/lib/security/cacerts/keystore.jks -storepass changeit

After import you can run the first command again to check if your certificate was added.

Sun/Oracle information can be found here.


You'll have to use the full path, e.g. c:\java\jdk\lib\security\cacerts
Like SimonSez said, you don't need a password, but if you want it, the default password is "changeit".
Also, in Windows you need to run the terminal as administrator, otherwise you get the error keytool error: java.io.FileNotFoundException ... (Access is denied) when you try to import your certificate.
Ah @SimonSez you are my god. But to add to it, one must specify trust store location and password as mentioned by @M Sach to get it to work.
Continued to have issues with Java 1.8. Needed to add cert as described and use Java < 1.8
A
Anggrayudi H

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!!


What do you do when the certificate expires? Repeat everything (yearly)?
Is there any way to do this programmatically?
For people dealing with the PKIX error, "Path does not chain with any of the trust anchors", this solution did not solve that problem for me unfortunately.
One Question - Does the aliasName is web address for which we are importing the certificate? For example, if URL is domain.site.com/pages/service.asmx then should alias be domain.site.com or complete URL(domain.site.com/pages/service.asmx) or should it also be prefixed with http:// or it is just an arbitrary name?
path:\lib\security> keytool -import -noprompt -trustcacerts -alias webCert -file webCertResource.cer -keystore c:/Users/Jackie/Desktop -storepass changeit I get "the system cannot find the file specified"
C
Community

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 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 with your domain (e.g. jossef.com)

replace 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);

// ...

Step 2 did the trick for me using SpringBoot and Tomcat 7. Thank you.
Do I have to use keytool from java that is used by tomcat?because on one server I can have many java
@vikifor yes. You can also run it for all java dirs installed on your system
This worked ! thanks a ton @JossefHarush for such an useful answer !
my issue was solved after adding @Jossef Harush's code segment into my code.
C
Community

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


A
Ali Ismayilov

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.


I had the same problem too. Calling an API with a Lets Encrypt Certificate may not work with older versions of Java because it isn't recognized by the trusted root certification authorities. Updating Java will solve this issue.
r
rogerdpack

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


This code is totally insecure and should not be used.
@user207421 Why is it insecure? What is happening in the code briefly.
This is skipping all certificate validations, basically it's allowing any certificate to be accepted. The way certs work is that there's a root certificate (literally) physically protected, at various certifying authorities. This certificate is then used to issue other secondary certs, which can be validated all the way back to the root certifying authority. This is skipping all the upstream checks, meaning that I can send in any ssl cert (even self generated) and your application will accept it as secure, even though my identity as a url is not verified.
a
avp

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.


R
Ryan Shillington

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.


This works wonderfully if the problem is that you are using an older version of java which does not have the latest certificates.
@atripathi how about a Mac?
There was something seriously wrong with your Java installation if the cacerts file was empty. You should have reinstalled it all.
Perhaps, but this solution worked and nothing was ever wrong afterwards.
y
y.an

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


Y
YaDa

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.


thats look like what im having. can you explain on how you added the intermediate certs and where. im using httpd revers proxy and not NGINX .
this helped me in my case becasue im using httpd: access.redhat.com/solutions/43575
With nginx, It only uses .key and .pem files for SSL config. First you convert .crt to .pem (simply: cp yourfile.crt yourfile.pem) and then for the SSL cert chain: you append .cer file to the last of .pem (cat yourfile.cer >> yourfile.pem)
B
Bahadir Tasdemir

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.


m
mons droid

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

t
tk_

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,

Download the site cert, Using Chrome Using Firefox Copy the certificate(ex:cert_file.cer) into the directory $JAVA_HOME\Jre\Lib\Security Open CMD in Administrator and change the directory to $JAVA_HOME\Jre\Lib\Security 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]

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!


D
Dave Richardson

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.


A
Abhishek

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

R
Radu Linu

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:

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


N
Nubian

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.


Same for me. An update from Java 1.8.0_91 to 1.8.0_121 solved the problem. I got the exception by using Apache HTTPClient.
I still have this issue using Oauth2 authentication
R
Rock

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.


S
Sergio Alonso

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.


R
Ramin Udash

I am using flutter and received this error out of nowhere. So, what basically happens is that the lines within your dependencies within android/build.gradle file such as:

  classpath 'com.android.tools.build:gradle:4.1.0'
  classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

require certification that the grade file downloads from the internet. But when there is something that's blocking the gradle to download those certificates, this is typically shown.

I tried exporting the certificate and adding it manually but it didn't seem to work for me. What worked for me, after countless head scratches, was disabling the proxies from your network preferences. It was somewhere mentioned that disabling Charles Proxy would fix it but at that moment, I was clueless what Charles was and what proxy was. And in my case, I did not have the Charles proxy thing so I went on with finding the proxies in the network preferences settings in Mac( it could be found somewhere in network settings for Windows). I had Socks enabled within the proxy. I disabled it and then again rebuilt the gradle and TA-DAH!!! It worked butter smooth.

There are a few things to remember. If you build your project right after disabling proxy without closing the network preferences tab, the disable proxies won't work and it will show the same error. Also if you've already built the project and you're running it again after disabling proxies, chances are it's gonna show the same error( could be due to IDE caches). How it worked for me: Restart the Mac, open a few tabs in the browser( for a few network calls), check the network preferences from system preferences>> wifi and disable proxies, close the system preferences app, and build the project.


b
bummi

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.


A
Apurva Singh

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 /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.


m
milfar dean

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.

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

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


e
espajava

I also have the same problem on Apache Tomcat/7.0.67 and Java JVM Version: 1.8.0_66-b18. With upgrading Java to JRE 1.8.0_241 and it seems that the issue was solved.


D
Dharman

If you are using JDK 11, the folder doesn't have JRE in it anymore. The location for the certs is jdk-11.0.11/lib/security/cacerts.


E
Emmajiugo

For OkHttpClient, this solution worked for me. It might help someone using the library...

try {

            String proxyHost = "proxy_host";
            String proxyUsername = "proxy_username";
            String proxyPassword = "proxy_password";

            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, "port goes here"));

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[]{};
                    }
                    @Override
                    public void checkClientTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                    }
                    @Override
                    public void checkServerTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                    }
                }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient client = new OkHttpClient().newBuilder()
                    .sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0])
                    .hostnameVerifier((hostname, session) -> true)
                    .connectTimeout(timeout, TimeUnit.SECONDS)
                    .proxy(proxy)
                    .proxyAuthenticator((route, response) -> {
                        String credential = Credentials.basic(proxyUsername, proxyPassword);
                        return response.request().newBuilder()
                                .header("Proxy-Authorization", credential)
                                .build();
                    })
                    .build();

            MediaType mediaType = MediaType.parse("application/json");
            RequestBody requestBody = RequestBody.create(payload, mediaType);

            Request request = new Request.Builder()
                    .url(url)
                    .header("Authorization", "authorization data goes here")
                    .method(requestMethod, requestBody)
                    .build();

            Response response = client.newCall(request).execute();

            resBody = response.body().string();

            int responseCode = response.code();

        } catch (Exception ex) {
        }

K
Kendar

Looking on various certificates contents and the ones generated through the standard openssl procedure i noticed that the AutorityKeyIdentifier was set, for the openssl root certificate, to itself. Probably there is a way to overcome that...but i don't know it...

Then i developed a small application with Java11 & BouncyCastle to generate root certificates and keys, now on github: https://github.com/kendarorg/JavaCaCertGenerator

The root certificates generated with this tool DOES NOT CONTAINS the AuthorityKeyIdentifier and can be installed with keytool directly on the cacert store. When i create then the csr and the ext file with the domain names this will be validated against the cacert store containing the root.. and no more handshake exceptions!

May be the cacert does not allow a recursive AuthorityKeyIdentifier? I don'know but i'll appreciate some review :)


R
R A U N A K

I was getting this error in Android Studio. SO i did this after a lot of research.

Password is changeit for cacert

Step 1 : Open CMD as Administrator

Step 2 : Type "Powershell"

Step 3 : start-process powershell -verb runas

Step 4 : Add all your Certificate in C:\Program Files\Android\Android Studio\jre\lib\security this location where cacert is available.

Step 5 : Go to Keytool directory Set-Location -Path "C:\Program Files\Android\Android Studio\jre\bin"

Step 6 : run this command in powershell .\keytool -importcert -trustcacerts -alias GiveNameforyourcertificate -file "C:\Program Files\Android\Android Studio\jre\lib\security\Replace With Your Certificate name.cer" -keystore cacerts

Step 7 : If Error comes as Certificate added (Access denied) then create a D drive partition(https://www.diskpart.com/windows-10/how-to-create-d-drive-from-c-drive-in-windows-10-0725.html) or move you file to d drive then add certificate

If you kept your file in D drive then only execute this

Step 8 : keytool -importcert -trustcacerts -alias Nameyourcertificate -file "D:\Certificatename.cer" -keystore cacerts

Step 9 : Check if certificate was added or not using this command .\keytool -list -keystore cacerts


W
Wirling

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


H
Harshavardhan

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>

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now