解决PKIX:unable to find valid certification path to requested target 的问题

问题的根本是:

缺少安全证书时出现的异常。

解决问题方法:

将你要访问的webservice/url....的安全认证证书导入到客户端即可。

以下是获取安全证书的一种方法,通过以下程序获取安全证书:

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

编译InstallCert.java,然后执行:java InstallCert hostname,比如:
java InstallCert www.twitter.com
会看到如下信息:

java InstallCert www.twitter.com
Loading KeyStore /usr/java/jdk1.6.0_16/jre/lib/security/cacerts...
Opening connection to www.twitter.com:443...
Starting SSL handshake...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 targetat com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:846)at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:815)at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1025)at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1038)at InstallCert.main(InstallCert.java:63)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targetat sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:221)at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:145)at sun.security.validator.Validator.validate(Validator.java:203)at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172)at InstallCert$SavingTrustManager.checkServerTrusted(InstallCert.java:158)at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320)at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:839)... 7 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targetat sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:236)at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:194)at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:216)... 13 moreServer sent 2 certificate(s):1 Subject CN=www.twitter.com, O=example.com, C=USIssuer  CN=Certificate Shack, O=example.com, C=USsha1    2e 7f 76 9b 52 91 09 2e 5d 8f 6b 61 39 2d 5e 06 e4 d8 e9 c7 md5     dd d1 a8 03 d7 6c 4b 11 a7 3d 74 28 89 d0 67 54 2 Subject CN=Certificate Shack, O=example.com, C=USIssuer  CN=Certificate Shack, O=example.com, C=USsha1    fb 58 a7 03 c4 4e 3b 0e e3 2c 40 2f 87 64 13 4d df e1 a1 a6 md5     72 a0 95 43 7e 41 88 18 ae 2f 6d 98 01 2c 89 68 Enter certificate to add to trusted keystore or 'q' to quit: [1]

输入1,回车,然后会在当前的目录下产生一个名为“ssecacerts”的证书。

将证书拷贝到$JAVA_HOME/jre/lib/security目录下,或者通过以下方式:
System.setProperty("javax.net.ssl.trustStore", "你的jssecacerts证书路径");

System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

注意:因为是静态加载,所以要重新启动你的Web Server,证书才能生效。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/296133.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

北大学霸隐居20年,王青松花光350万后,如今怎么样了?

全世界只有3.14 % 的人关注了爆炸吧知识传说我国&#xff0c;本科生遍地走&#xff0c;研究生多如狗。但一估算&#xff0c;从1977年高考恢复以来&#xff0c;国内现在的本科率竟然还不到5%。这样一想&#xff0c;30多年前的本科生数量肯定更少&#xff0c;也更珍贵。如果是北大…

如何在 Dapper.NET 中使用事务?

咨询区 Amit&#xff1a;我的项目中使用 dapper.net 做数据库连接框架&#xff0c;有一个需求需要在多个表上执行多次插入操作&#xff0c;我想把它 事务化&#xff0c;但我看 dapper 并没有提供类似的方式。请问我该如何使用 dapper 来做这项工作呢&#xff1f;回答区 Newteq …

文件给制实施规定的实例(GB8567-88)

尽管在文件编制中存在着很多灵活性&#xff0c;然而&#xff0c;文件的编制确实是非常必要的&#xff0c;其意义如前所述。为了控制这种灵活性&#xff0c;保证文件编制能达到应该达到的目的&#xff0c;对于具体的软件开发任务&#xff0c;应编制的文件的种类、详细程度应取决…

python 内存数据库下载,Python 文件存储和数据库

Python 中数据存储的方式和其他语言没什么区别&#xff0c;主要分为两个方面&#xff1a;文件存储和数据库存储。文件存储文件存储的方法也分为很多种&#xff0c;主要包括&#xff1a;Python 内置方法NumPy 模块方法os 模块方法csv 模块方法Python 内置方法在不需要借助任何外…

c#10中的namespace

A、namespace是c#用来管理类型隔离的关键字&#xff0c;在不同的namespace下可以相同名称的类型&#xff0c;并且namespace是可以嵌套的。Demo01.csnamespace NameSpaceDemo {internal class Demo01Class{ }namespace NSDemo01{internal class Demo01Class{}}namespace NSDemo…

岛国小姐姐来例假时,男朋友背着她偷偷查手机......

1 大猪蹄子们都好好学学▼2 人形扫地机&#xff1f;&#xff1f;&#xff1f;▼3 妈&#xff0c;看下你儿子大学四年积攒的宝藏▼4 你以为养老院很无聊&#xff1f;▼5 这个事是全世界统一的吗&#xff1f;▼6 爸爸&#xff1a;今天做个温柔的人吧▼7 那些隐藏在民间的车…

mysql-普通查询(General Query)慢查询(Slow Query)相关日志配置

2019独角兽企业重金招聘Python工程师标准>>> 配置 配置方法一: 服务启动时 # vi /etc/my.cnf ... log-outputTABLE,FILE general-log1 slow-query-log1# systemctl restart mysqldlog-output默认是FILE,还有个值是NONE,就不输出日志了.我这里演示的是表和日志文件都…

eclipse myeclipse 快捷键

MyEclipse 快捷键1(CTRL) ------------------------------------- Ctrl1 快速修复 CtrlD: 删除当前行 CtrlQ 定位到最后编辑的地方 CtrlL 定位在某行 CtrlO 快速显示 OutLine CtrlT 快速显示当前类的继承结构 CtrlW 关闭当前Editer CtrlK 快速定位到下一个 CtrlE…

委托与事件

首先多谢网上的大牛们无私地分享自己的经验&#xff0c;让我这样的小鸟能站在巨人的肩膀上不断前进&#xff01; 参考网址&#xff1a;http://www.knowsky.com/395937.html&#xff08;参考1&#xff09; http://hi.baidu.com/zhangguilin/blog/item/9d34dc17a088ff0ac83d6d08.…

适配器简介

STL 适配器分为 函数对象适配器、迭代器适配器 和 容器适配器 3种&#xff0c;分别完成对应的类型转换。 举例子容易&#xff0c;比如电源插座&#xff0c;3个头的插头插不进两个头的插座&#xff0c;就需要一个适配器。 1、函数适配器&#xff1a; 在stl程序里&#xff0c;有的…

他让全世界凶手睡不着觉,现实版福尔摩斯,退休了4次又被拽回来工作,无敌实在是太寂寞了~...

全世界只有3.14 % 的人关注了爆炸吧知识今天要说一位最近在中国圈粉无数萌萌哒老爷爷他是《挑战不可能》里的李博士也是世界上最牛逼的刑侦鉴识专家DrHenryLee李昌钰人称现实版福尔摩斯他是全球身价最高的鉴识专家之一据说工作酬劳是10000美元/时如果哪个案子他都破不了那这个c…

集成Dapr的 Azure 容器应用

微软在 Ignite 2021 大会上发布了预览版的Azure Container Apps&#xff0c;这是一个完全托管的无服务器容器运行时&#xff0c;用于大规模构建和运行现代应用程序。从2021 年 11 月 2 日起&#xff0c;Azure 容器应用程序可在公共预览中使用。虽在服务到达 GA 之前&#xff0c…

jsp iframe嵌入php,jsp嵌套iframe从iframe中表单提交并传值到外层_html/css_WEB-ITnose

今天因需求迭代 更改元来代码 遇到了这么个问题就是想在 iframe中提交后进行整个页面的跳转 并把iframe中的值传到外层jsp大概就是这个样子外层 a.jsp内层 b.jsp于是想当然的开始码代码打算用js进行赋值 在b.jsp中 写个js$(#d).val();虽然能获取到隐藏域的值 但 外层的值并没有…

浅谈SQL注入风险 - 一个Login拿下Server(转)

前两天&#xff0c;带着学生们学习了简单的ASP.NET MVC&#xff0c;通过ADO.NET方式连接数据库&#xff0c;实现增删改查。 可能有一部分学生提前预习过&#xff0c;在我写登录SQL的时候&#xff0c;他们鄙视我说&#xff1a;“老师你这SQL有注入&#xff0c;随便都能登录了。不…

java笔试面试经典问题

java面试笔试题大汇总 JAVA相关基础知识 1、面向对象的特征有哪些方面 1.抽象&#xff1a; 抽象就是忽略一个主题中与当前目标无关的那些方面&#xff0c;以便更充分地注意与当前目标有关的方面。抽象并不打算了解全部问题&#xff0c;而只是选择其中的一部分&#xff0…

设计模式建议学习顺序

学习顺序设计模式常用程度适用层次引入时机结构复杂度变化实现体现的原则1Factory Method很常用代码级编码时简单子类的实例化对象的创建工作延迟到子类开闭原则2Singleton很常用代码级、应用级设计时、编码时简单唯一实例封装对象产生的个数 3Facade很常用应用级、构架级设计时…

MSFT Outlook VBA处理新邮件的方法

俺们有两个邮箱&#xff0c;1个外部的邮箱1&#xff08;outlook&#xff09;&#xff0c;1个内部邮箱0&#xff08;lotus notes&#xff09;。想要outlook邮箱收到新邮件之后判断一下subject的内容&#xff0c;如果是"kkk:"开头&#xff0c;则将"kkk:"后面…

炸了!中国学者首次被Science撤稿,与之前首次被Nature撤稿的教授来自同一所大学……...

全世界只有3.14 % 的人关注了爆炸吧知识两次撤稿并非学术造假&#xff1f;国庆假期结束的第一天&#xff0c;Science杂志将中国地质大学宋怀兵副教授两个月前发表的文章进行了撤稿处理。这也是新中国建国以来&#xff0c;首次被Science撤稿的论文。其实早在8月&#xff0c;Scie…

linux 查询oracle情况,在Linux下使用SQLPlus查看Oracle数据库表空间及使用率

在Linux下进入SQLPlus&#xff0c;# su – oracle$ sqlplus / as sysdbaSQL>查看一个表空间所对应的数据文件SQL>select file_name from dba_data_fileswhere tablespace_name’BING’;FILE_NAME———————————————————————————————————…

如何编写干净流畅的Web API测试

前言当我们为Web API编写测试用例时&#xff0c;代码基本是这样的&#xff1a;public class UnitTest1 {private readonly TestServer _server;private readonly HttpClient _client;public UnitTest1(){// Arrange_server new TestServer(new WebHostBuilder().UseStartup<…