请求https报错证书校验失败(javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX

这篇具有很好参考价值的文章主要介绍了请求https报错证书校验失败(javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

项目场景:

请求https报错证书校验失败(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)

问题描述

项目中请求第三方https的URL,报错ssl证书校验失败

14:33:55.195 [main] ERROR com.bd.common.utils.OKHttpUtil - context
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(Alerts.java:192)
	at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
	at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
	at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
	at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
	at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
	at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
	at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
	at com.squareup.okhttp.internal.io.RealConnection.connectTls(RealConnection.java:192)
	at com.squareup.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:149)
	at com.squareup.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
	at com.squareup.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
	at com.squareup.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
	at com.squareup.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
	at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)

原因分析:

ssl校验失败有两种可能,一种是服务端ssl证书配置错误,一种是客户端请求的是非信任的https地址,客户端不信任该https的ssl证书。怀疑是使用了自签名证书,非各大厂提供签名证书

解决方案:

该问题有两种请求方案文章来源地址https://www.toymoban.com/news/detail-780363.html

  1. 手动下载ssl证书
    (1)在浏览器地址栏里找到“证书信息”->“详细信息”->“复制到文件”->选择DER编码二进制X.509(.CER)(D) 导出证书,如证书名为pro1.cer;
    (2)将pro1.cer上传至服务器/usr/java;
    (3)执行keytool -import -alias pro1 -keystore /usr/java/jdk1.8.0/jre/lib/security/cacerts -file /usr/java/pro1.cer;
    (4)输入密码:changeit
    (5)查看证书库keytool -list -keystore /usr/java/jdk1.8.0/jre/lib/security/cacerts|grep pro1.cer,如找到到 证书信息,代表完成导入。
    (6)回到程序,调试java程序不再报错。
  2. 使用提供的工具类自动下载证书
    使用该工具过程中,工具类会提示用户选择是否将证书添加到信任存储中。用户可以输入证书的序号,将指定的证书添加到信任存储中。
package com.sword.lasms.commons.httpClient;

/*
 * 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.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

/**
 *  发送 Https 请求报错:PKIX: unable to find valid certification path to requested target
 *
 * 问题的根本是:缺少安全证书时出现的异常。
 * 解决问题方法:将要访问的webservice/url....的安全认证证书导入到客户端即可。
 *
 * 以下是获取安全证书的一种方法,通过以下程序获取安全证书
 * (仅需要修改参数 args )
 *
 */
public class InstallCert {

    public static void main(String[] args) throws Exception {
//        args= new String[]{"sgdzpic.3322.org:20008"};  // 填写要访问的 url:端口
        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);
        }
    }

}

到了这里,关于请求https报错证书校验失败(javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 证书异常导致:javax.net.ssl.SSLHandshakeException: sun.security.validator

            当我们应用程序 访问设有https证书的服务 时,若 JRE未安装指定证书 则会提示标题的报错,此时有 两种方式 解决该问题:        按照实际场景,可从信息科、网络处等部门协调获取证书,也可以直接从安装证书的电脑上,通过浏览器下载证书,本文介绍后一种

    2024年01月17日
    浏览(38)
  • 解决远程调用三方接口:javax.net.ssl.SSLHandshakeException报错

    最近在对接腾讯会议API接口,在鉴权完成后开始调用对方的接口,在此过程中出现调用报错:javax.net.ssl.SSLHandshakeException。 当你在进行https请求时,JDK中不存在三方服务的信任证书,导致出现错误javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX路径构建失败。

    2024年02月13日
    浏览(49)
  • 解决 javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX 路径构建失败

    之前一个项目使用Java请求客户提供的接口时,返回报错如下: javax.net.ssl.SSLHandshakeException 错误通常表示 SSL 握手失败。这意味着在建立 SSL 连接时,Java 安全管理器无法构建一个有效的证书路径,从而无法找到有效的证书路径来验证目标站点的证书,触发此错误信息的调用方

    2024年02月04日
    浏览(47)
  • 解决报错:javax.net.ssl.SSLHandshakeException: No appropriate protocol

    使用对象存储进行文件上传时报错 注:该问题只要需要用到http的都有可能出现,不是只针对对象存储 jdk 的 java.security 文件存在配置问题 1、查看当前服务器使用的 jdk 版本 命令: java -version 2、查看该jdk的安装目录 命令: find / -name java.security 这里选择通过搜索 java.security 来

    2024年01月24日
    浏览(46)
  • javax.net.ssl.SSLHandshakeException No appropriate protocol报错解决方案

    用java开发了一个简单的***发送邮件***的程序,本地运行正常,但是上传到服务器就出现报错: 方案一 [原文参考地址](javax.net.ssl.SSLHandshakeException: No appropriate protocol报错解决_蓝缘的博客-CSDN博客) ​ 1、找到jdk目录/jre/lib/security/java.security,去掉jdk.tls.disabledAlgorithm中的SSLv3、T

    2023年04月15日
    浏览(37)
  • WGCLOUD监控sqlserver报错javax.net.ssl.SSLHandshakeException: The server selected protocol version TLS10

    翻译成中文:SqlServer 服务器只接受 TLS1.0,但是客户端给的是 TLS1.2。 找到 jdk11confsecurity 下java.security 文件 1. 把 jdk.tls.disabledAlgorithms 配置项中 TLSv1 删除,这样  TLS1.0 就可以使用了。 #jdk.tls.disabledAlgorithms=SSLv3, TLSv1, TLSv1.1, RC4, DES, MD5withRSA, #    DH keySize 1024, EC keySize 224, 3D

    2024年02月06日
    浏览(44)
  • Debezium报错处理系列之九十四: javax.net.ssl.SSLHandshakeException: Remote host terminated the handshake

    研究Debezium技术遇到的各种错误解决方法系列文章传送门: Debezium从入门到精通系列之:百篇系列文章汇总之研究Debezium技术遇到的各种错误的解决方法

    2024年01月18日
    浏览(34)
  • javax.net.ssl.SSLHandshakeException

    解决办法升级jdk版本或者修改jdk文件 1、对于服务器来说要支持域名并且不进行ssl证书校验,需要升级到jdk1.8的201版本及以上 2、修改…JavaJDKjrelibsecurity目录下java.security文件,添加下面语句到文件内容中

    2024年02月11日
    浏览(43)
  • 请求第三方Https地址忽略SSL证书校验

    说明:个人使用记录 需要在请求之前忽略ssl协议,这里是直接使用静态方法初始化时就执行了 也需要在请求接口之前忽略SSL

    2024年04月10日
    浏览(50)
  • Macos jdk ssl javax.net.ssl.SSLHandshakeException完美解决

    报了这么一个错误 javax.net.ssl.SSLHandshakeException: Remote host terminated the handshake 网上一大把,测试不能用,谷歌了一下,发现少配置了一个环境变量。 System.setProperty(\\\"jdk.tls.useExtendedMasterSecret\\\", \\\"false\\\");//设置环境变量 /Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home/jre/lib/security/java.se

    2024年02月13日
    浏览(64)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包