Java在请求某些不受信任的https网站时会报:PKIX path building failed

解决方法一:使用keytool手动导入证书,为JRE环境导入信任证书

参考:http://www.cnblogs.com/wanghaixing/p/5630070.html

方法二:使用代码下载证书保存

参考:https://blog.csdn.net/frankcheng5143/article/details/52164939

方法三:服务器不信任我们自己创建的证书,所以在代码中忽略证书信任问题。

参考:http://mengyang.iteye.com/blog/575671

最后注意:检查eclipse/myeclipse的JDK或JRE,是否为你导入证书的JRE。

注意:myeclipse是自带JDK的,JDK中自带JRE,而我们通过命令导入的jre是系统环境变量下path的jre。

两者很可能不是同一个,要改myeclipse的配置。(具体操作很简单,windows-->preferences-->搜索jre)

方法二代码实现

功能:把目标host证书保存到jre/lib/security/jssecacerts文件,亲测有效

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.*;
import javax.net.ssl.*;
import java.security.cert.*;
import org.junit.Test; public class certUtils {
private int port = 443;
private char[] passphrase="changeit".toCharArray(); /**
* @param host 例:www.80s.tw
* @param port https默认为443端口
* @param passphrase keyStore密码
*/
public void installCert(String host, int port, char[] passphrase) {
//文件分隔符
char SEP = File.separatorChar;
//获取jre/lib/security目录
File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP
+ "security");
//新建文件jre/lib/security/jssecacerts,向文件输出时文件才真正创建
File file = new File(dir, "jssecacerts");
//jssecacerts文件不存在时,获取jre/lib/security/cacerts文件索引
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
System.out.println("Loading KeyStore " + file + "...");
try {
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);
try {
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(10000);
System.out.println("Starting SSL handshake...");
socket.startHandshake();
socket.close();
System.out.println("No errors, certificate is already trusted");
} catch (Exception e) {
e.printStackTrace();
} X509Certificate[] chain = tm.chain;
if (chain == null) {
return;
} BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = 0; i < chain.length; i++) {
X509Certificate cert = chain[i];
sha1.update(cert.getEncoded());
md5.update(cert.getEncoded());
}
// 默认证书链第一个
int index = 0;
X509Certificate cert = chain[index];
String alias = host + "-" + (index + 1);
ks.setCertificateEntry(alias, cert); // keyStore保存到文件jssecacerts
File jssecacerts = new File(dir, "jssecacerts");
OutputStream out = new FileOutputStream(jssecacerts);
ks.store(out, passphrase);
out.close(); System.out.println("-----打印cert-----");
System.out.println(cert);
} catch (Exception e) {
e.printStackTrace();
}
} private final char[] HEXDIGITS = "0123456789abcdef".toCharArray(); private 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 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);
}
}
}

  

查看证书

keytool -list -v -alias aurora -keystore "C:/Program Files/Java/jdk1.7.0_03/jre/lib/security/cacerts" -storepass changeit  
这条命令是在JDK安装的密钥库中,查找别名是aurora的证书,密钥库口令是changeit。

删除证书

keytool -delete -alias aurora -keystore "C:/Program Files/Java/jdk1.7.0_03/jre/lib/security/cacerts" -storepass changeit
删除别名是aurora的证书。

方法三代码实现

  只要在创建connection之前调用两个方法:

  由于有网友这么说:这样做是放弃了证书的认证,那你们用https还有什么意义呢?就好像搭建了一个https的server,最后在认证失败的时候放弃认证,直接选择信任,那么这个https的server就沦落为一个http的server了,而且性能要比http差

  在下就没有测试,请自行测试。

trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);

  

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

  

解决PKIX path building failed的问题的更多相关文章

  1. 从头解决PKIX path building failed

    从头解决PKIX path building failed的问题 本篇涉及到PKIX path building failed的原因和解决办法(包括暂时解决和长效解决的方法),也包括HTTP和HTTP ...

  2. 解决PKIX path building failed

    起因 上周在生产环境部署时,把安全证书加到k8s-ingress中时发现报该错误 解决 找网上解决方案,因为这种问题相对比较少见,也没百度,直接谷歌,找到解决方案如下:https://stackove ...

  3. 解决 java 使用ssl过程中出现"PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target"

    今天,封装HttpClient使用ssl时报一下错误: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorExc ...

  4. 解决PKIX(PKIX path building failed) 问题 unable to find valid certification path to requested target

    最近在写java的一个服务,需要给远程服务器发送post请求,认证方式为Basic Authentication,在请求过程中出现了 PKIX path building failed: sun.se ...

  5. 抓取https网页时,报错sun.security.validator.ValidatorException: PKIX path building failed 解决办法

    抓取https网页时,报错sun.security.validator.ValidatorException: PKIX path building failed 解决办法 原因是https证书问题, ...

  6. 解决CAS单点登录出现PKIX path building failed的问题

    在一次调试中,出现了这个错误: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderExceptio ...

  7. 解决 sun.security.validator.ValidatorException: PKIX path building failed

    今天用java HttpClients写爬虫在访问某Https站点报如下错误: sun.security.validator.ValidatorException: PKIX path buildin ...

  8. jsoup访问页面: PKIX path building failed

    在用jsoup访问页面时报错javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX p ...

  9. 异常信息:javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed

    上周五遇到一个问题,工程本地编译运行正常,打包本地tomcat运行也正常.部署到测试环境报错: 2017-05-05 09:38:11.645 ERROR [HttpPoolClientsUtil.j ...

随机推荐

  1. 【CF1252L】Road Construction(基环树,最大流)

    题意:给定一张n点n边无重边自环的无向图,刚开始每条边都没有被选择,每条边上有一个颜色集合,必须从中选择一种 有K个工人,每个工人有颜色a[i],需要把工人分配到与其颜色相同的边上 问是否能有一种使得 ...

  2. [BZOJ4456][ZJOI2016]旅行者:分治+最短路

    分析 类似于点分治的思想,只统计经过分割线的最短路,然后把地图一分为二. 代码 #include <bits/stdc++.h> #define rin(i,a,b) for(regist ...

  3. sar性能监控

    1.安装sar: yum -y install sysstat 第一次使用sar命令会提示如下错误:“无法打开 /var/log/sa/sa13: 没有那个文件或目录”. 这里的值13是当天的日期,如 ...

  4. JavaScript难点笔记

    前言 由于工作需求重新回顾了一下JavaScript,以下内容是我以前的学习笔记和其他参考资料整理完善后的内容,都是常用到的,使用频率比较高的,自己必须得精通的知识点的总结,便以后再复习参考. 第一章 ...

  5. js中的 for, for in, for of foreach,filter使用

    下面是对数组进行循环 var array = [ { id: , name: 'ohzri', birth: '1999.09.09', city: '湖北', salary: }, { id: , ...

  6. Electron-Vue工程初始化,以及需要掌握的相关知识

    1.安装nodejs 下载地址:http://nodejs.cn/ 需要重启系统 2.安装electron npm install electron -g 3.安装vue npm install vu ...

  7. linux修改时区为东八时区,北京时间,上海时间

    ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime echo "Asia/Shanghai" > /etc/tim ...

  8. 基于DRF的图书增删改查练习

    功能演示 信息展示 添加功能 编辑功能 删除功能 DRF构建后台数据 本例的Model如下 from django.db import models class Publish(models.Mode ...

  9. VS2010远程调试C#程序

    场景: 客户的计算机运行程序出现异常,由于办公场所不在一起,无法直接在客户的机器上调试.此时希望可以直接在开发人员的计算机(本地机器)上远程调试客户机上的软件. 假设: 本地机器的系统账户为 GIS, ...

  10. linux(centOS7)的基本操作(二) 目录和文件管理

    1.显示当前工作目录的绝对路径 pwd 2.显示当前工作目录下的子目录和文件 ls [-l] [-h] [-a] 如果只调用ls,子目录和文件会简单的罗列出来,-l表示将其以详细列表的形式展示,-h表 ...