分析解决 PKIX path building failed 的问题

调用https接口报如下错误:

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


非常感谢这位博主的文章:

https://blog.51cto.com/u_15475949/4884742

现象和我的完全一样,解决方式的流程上也没问题,最后也解决了我的问题。


阅读下文前,先看完并熟悉上面的文章,如果您的过程非常顺利,后面文请无视。


这里列出我执行上述流程时遇到的问题:

背景:

和上文一样,这里详细介绍下,后面的问题2 就省事了。

  1. 客户给了https 的 rustful 接口,让我们取数据做业务处理。
  2. postman 工具验证了接口没问题。
  3. 本地开发环境无法访问,报本文标题的错误。


 

我是 win10 系统。

问题1:

在生成证书的时候,由于我环境的原因,无法用 cmd 命令直接运行,但却可以在 Idea 这个IDE 上执行,很诡异。(个人不是很理解)

所以我需要在 IDE 里执行时,加入参数,采用如下的方式,(在黄色区域放入 域名):

执行的开始日志,会有报错,但后面日志就开始生成了,很顺利。

注意:最后的证书 名称为 jssecacerts ,所处位置为 项目根目录。


问题 2 与分析:

我发现只是我本地研发环境有这个报错。

由于之前也做过很多微服务间 https 的 rustful 接口调用,从未遇到过这个问题。

所以最初,就将代码放到服务器上试试运气,发现居然能正常访问这个域名,并没有报错。

我目前公司很大,各个域名分布很杂乱。所以 用 ping 命令看了下 各自域名 ip。

发现我本地是公司内部局域网,服务器是公网域名,而客户域名是公网域名。

这是我意识到,之前做的 https 的虽然都有公网域名,互相的调用也用的时公网域名,但其实都属于一个内部局域网(因为一起采购的)。

我发现确实和之前的的rustful 接口不太一样。而这次客户 的公网ip 是完全独立的公司接口。


 下面贴上核心内容:

生成证书的程序:

/**
 * @FileName  获取安全证书
 * @ClassName InstallCert
 * @Author Liu
 * @Date 2020/10/26 15:45
 */
/*
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.*;
import java.net.URL;

import java.security.*;
import java.security.cert.*;

import javax.net.ssl.*;

public class InstallCert {

    public static void main(String[] args) throws Exception {
        String host;
        int port;
        char[] passphrase;
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
            return;
        }

        File file = new File("jssecacerts");
        if (file.isFile() == false) {
            char SEP = File.separatorChar;
            File dir = new File(System.getProperty("java.home") + SEP
                    + "lib" + SEP + "security");
            file = new File(dir, "jssecacerts");
            if (file.isFile() == false) {
                file = new File(dir, "cacerts");
            }
        }
        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] {tm}, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        BufferedReader reader =
                new BufferedReader(new InputStreamReader(System.in));

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println
                    (" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
        String line = reader.readLine().trim();
        int k;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
            System.out.println("KeyStore not changed");
            return;
        }

        X509Certificate cert = chain[k];
        String alias = host + "-" + (k + 1);
        ks.setCertificateEntry(alias, cert);

        OutputStream out = new FileOutputStream("jssecacerts");
        ks.store(out, passphrase);
        out.close();

        System.out.println();
        System.out.println(cert);
        System.out.println();
        System.out.println
                ("Added certificate to keystore 'jssecacerts' using alias '"
                        + alias + "'");
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 3);
        for (int b : bytes) {
            b &= 0xff;
            sb.append(HEXDIGITS[b >> 4]);
            sb.append(HEXDIGITS[b & 15]);
            sb.append(' ');
        }
        return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {

        private final X509TrustManager tm;
        private X509Certificate[] chain;

        SavingTrustManager(X509TrustManager tm) {
            this.tm = tm;
        }

        public X509Certificate[] getAcceptedIssuers() {
            throw new UnsupportedOperationException();
        }

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

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            this.chain = chain;
            tm.checkServerTrusted(chain, authType);
        }
    }

}

用上面的程序,直接运行,带上 你要认证的域名(域名类似格式:xxx.com    记得去除 https://这些没用的头,和后面那些没用的路径。)

命令核心:

(1)编译:javac InstallCert.java

(2)执行:java  InstallCert  你的https域名,比如:java  InstallCert  xxx.com

 输入1(默认就是1,其实不用输入),然后直接回车,会在相应的目录下产生一个名为‘jssecacerts’的证书。

脚本在当前目录。如果是idea,在项目根目录。

复制证书到指定目录:

(4)将证书copy到$JAVA_HOME/jre/lib/security目录下,

或者

通过以下方式(这个方式没有验证过):

         System.setProperty("javax.net.ssl.trustStore", "C:\\Keystore\\jssecacerts");

    注意:要重新启动你的应用服务器,因是静态加载,证书才能被运用上。
 

该错误提示表明在使用httpClient时,出现了PKIX路径构建失败的错误。这通常是由于SSL证书问题引起的。根据引用的信息,错误信息中提到了sun.security.validator.ValidatorException: PKIX path building failed,这意味着在验证服务器的证书时出现了问题。引用提供了解决方案,即将目标网站的证书导入到jdk中。 为了解决这个问题,你可以按照以下步骤来导入证书: 1. 打开命令提示符(cmd)窗口。 2. 切换到jdk安装路径下的`jre\lib\security`目录,例如`C:\Program Files\Java\jdk1.8.0_73\jre\lib\security`。 3. 执行以下命令来导入证书: ``` keytool -import -keystore "%JAVA_HOME%\jre\lib\security\cacerts" -file G:\ssodemo.crt -alias ssodemo ``` 其中,`G:\ssodemo.crt`是要导入的证书文件路径,`ssodemo`是给证书取的别名。 这样,通过将目标网站的证书导入到jdk中,就可以解决PKIX路径构建失败的问题,从而解决httpClient报错的问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [PKIX path building failed问题](https://blog.csdn.net/weixin_46505978/article/details/128281379)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [编译报错:PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilder](https://blog.csdn.net/bob601450868/article/details/130035742)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Java的HttpClient出现PKIX path building failed问题](https://blog.csdn.net/weixin_42376402/article/details/124337007)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值