PKIX path building failed

简介: 生产环境业务流程走不通,查了es后以为请求其他服务器资源有错,错误如下:[http-nio-9097-exec-1] sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targetjava


生产环境业务流程走不通,查了es后以为请求其他服务器资源有错,错误如下:

[http-nio-9097-exec-1] sun.security.validator.ValidatorException: PKIX path building fai
led: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderExceptio
n: unable to find valid certification path to requested target
        at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) ~[?:1.8.0_201]
        at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946) ~[?:1.8.0_201]
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:316) ~[?:1.8.0_201]
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:310) ~[?:1.8.0_201]
        at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1639) ~[?:1.8.0_201]
        at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:223) ~[?:1.8.0_201]
        at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1037) ~[?:1.8.0_201]
        at sun.security.ssl.Handshaker.process_record(Handshaker.java:965) ~[?:1.8.0_201]
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1064) ~[?:1.8.0_201]
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367) ~[?:1.8.0_201]
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395) ~[?:1.8.0_201]
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379) ~[?:1.8.0_201]
        at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) ~[?:1.8.0_201]
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) ~[?:1.8.0_201]
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1564) ~[?:1.8.0_201]
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492) ~[?:1.8.0_201]
        at com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl.getInputStream(HttpsURLConnectionOldImpl.java:233) ~[?:1.8.0_201]
        at org.apache.commons.io.FileUtils.copyURLToFile(FileUtils.java:1506) ~[commons-io-2.5.jar!/:2.5]
        at com.cngongbao.basic.platform.util.FileUtil.copyURLToFile(FileUtil.java:139) ~[common-2.3-SNAPSHOT.jar!/:2.3-SNAPSHOT]
本以为请求其他服务器有证书错误,但是后面看日志发现copyURLToFile是自己服务器的资源,本质是java在访问https资源时的证书信任问题。Windos浏览器访问https资源,发现证书不可信任,一般会弹框告诉用户,对方的证书不可信任,是否继续或者无法进入之类这个大家经常遇到。
Java虚拟机并不直接使用操作系统的keyring,而是有自己的security manager。与操作系统类似,jdk的security manager默认有一堆的根证书信任。如果用java访问https资源,发现证书不可信任,就会有上述报错。网上查询后发现目前的两种解决办法。一种是对服务器添加证书导入到jdk的证书路径。两一种是代码加入忽略https信任代码块。

第一种的实现方案

编译:javac InstallCert.java

运行:java InstallCert 要访问的网址

最后面会输出:

Enter certificate to add to trusted keystore or 'q' to quit: [1]

输入1,然后直接回车,会在相应的目录下产生一个名为‘jssecacerts’的证书。将证书copy到$JAVA_HOME/jre/lib/security目录下

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

}

 第二种实现方案

HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            System.out.println("Warning: URL Host: " + urlHostName + " vs. "
                               + session.getPeerHost());
            return true;
        }
    };
 
 private static void trustAllHttpsCertificates() throws Exception {
 javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
 javax.net.ssl.TrustManager tm = new miTM();
 trustAllCerts[0] = tm;
 javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
 .getInstance("SSL");
 sc.init(null, trustAllCerts, null);
 javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
 .getSocketFactory());
 }
 
 static class miTM implements javax.net.ssl.TrustManager,
 javax.net.ssl.X509TrustManager {
 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
 return null;
 }
 
 public boolean isServerTrusted(
 java.security.cert.X509Certificate[] certs) {
 return true;
 }
 
 public boolean isClientTrusted(
 java.security.cert.X509Certificate[] certs) {
 return true;
 }
 
 public void checkServerTrusted(
 java.security.cert.X509Certificate[] certs, String authType)
 throws java.security.cert.CertificateException {
 return;
 }
 
 public void checkClientTrusted(
 java.security.cert.X509Certificate[] certs, String authType)
 throws java.security.cert.CertificateException {
 return;
 }
 }

在访问https资源前,调用trustAllHttpsCertificates();

欢迎有其他方案或问题留言交流

 参考文档:
http://blog.csdn.net/mingli198611/article/details/8055261《HTTP和HTTPS详解》
http://www.cnblogs.com/wupher/archive/2012/08/05/2623561.html《使用Keytool为JDK添加https证书信任》
http://mengyang.iteye.com/blog/575671《解决PKIX path building failed的问题》
java在访问https资源时,忽略证书信任问题_lizeyang的博客-CSDN博客_java忽略证书《java在访问https资源时,忽略证书信任问题》

Java 和 HTTP 的那些事(四) HTTPS 和 证书相关_somnus_小凯的博客-CSDN博客《Java 和 HTTP 的那些事(四) HTTPS 和 证书相关》

目录
相关文章
|
6月前
|
安全 Java API
Eclipse 打开marketplace 报PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
网上有很多解决的帖子,我这里只是记录一下方便自己查阅 主要原因是java本身需要证书 1、按导入安全证书的方法解决
809 0
Eclipse 打开marketplace 报PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
|
3月前
|
Web App开发 Java 网络安全
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
562 0
|
3月前
|
编译器 API C++
【Matlab】解决使用Mex 报错There was a problem creating the mex file for Real Time Execution ,Please ensure y
解决Matlab使用Mex时出现的"Real Time Execution"错误的步骤,即通过安装"MATLAB 支持 MinGW-w64 C/C++ 编译器"这个包来确保编译器设置正确。
60 0
ERROR: Encountered errors while bringing up the project.
ERROR: Encountered errors while bringing up the project.
167 0
|
Python
ERROR: Failed building wheel for osgeo
ERROR: Failed building wheel for osgeo
353 0
|
安全 Java 应用服务中间件
分析解决 PKIX path building failed 的问题
分析解决 PKIX path building failed 的问题
496 0
|
Java Linux
error: Failed dependencies: libjvm.so()(64bit) is needed by (installed)
error: Failed dependencies: libjvm.so()(64bit) is needed by (installed)
error: Failed dependencies: libjvm.so()(64bit) is needed by (installed)
|
安全 Java Apache
异常:PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/catoop/article/details/80819638 问题 java使...
23103 0
|
并行计算 PyTorch 算法框架/工具
CUDA unknown error - this may be due to an incorrectly set up environment 问题解决
CUDA unknown error - this may be due to an incorrectly set up environment 问题解决
CUDA unknown error - this may be due to an incorrectly set up environment 问题解决
Your project setup is incompatible with our requirements due to following reasons:
Your project setup is incompatible with our requirements due to following reasons:
582 0