Java# 请求https时证书不可信 PKIX SunCertPathBuilderException:unable to find valid certification....
Posted LRcoding
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java# 请求https时证书不可信 PKIX SunCertPathBuilderException:unable to find valid certification....相关的知识,希望对你有一定的参考价值。
背景:当使用 Java 请求 https协议的服务时,报 ’unable to find valid certification path to requested target’ 异常
解决方式1:将请求服务的证书导入到 JDK的 cacerts中
-
通过浏览器先访问网址,然后将证书进行导出(以 Edge浏览器为例)
-
以管理员身份打开cmd,进入到 “%JAVA_HOME%/jre/lib/\\security”目录下,执行以下命令
keytool -import -keystore cacerts -alias server -file 证书的位置 -file:指定证书文件的位置 -keystore:安装证书到的位置 -alias:指定证书的别名
-
输入密钥库默认口令:changeit,输入 “Y”信任此证书即可
解决方式2:使用Java类生成证书
- InstallCert.java类会连接到给定的host,开始握手过程。如果出现异常会打印到控制台并且会显示服务端所使用的证书,此时它会问是否要把证书加入到keystore中。
- 如果不想加,输入”q”,否则输入”1”.
- 当输入”1”后,InstallCert.java 会显示证书的有关信息,然后把证书导入到一个名为”jssecacerts”的keystore中(生成在当前目录),只需要把这个文件拷贝到 %JAVA_HOME%/jre/lib/security 目录中即可
import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class InstallCert
public static void main(String[] args)
try
installCert("https://www.baidu.com", 443);
catch (Exception e)
e.printStackTrace();
private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
/**
* 安装证书
*
* @param requestUrl 请求https服务的地址
* @param port https默认端口为 443
* @throws Exception
*/
public static void installCert(String requestUrl, int port) throws Exception
// 密钥库默认口令,一般默认changeit
String pwd = "changeit";
char[] passphrase = pwd.toCharArray();
File file = new File("jssecacerts");
if (!file.isFile())
char sep = File.separatorChar;
File dir = new File(System.getProperty("java.home") + sep + "lib" + sep + "security");
file = new File(dir, "jssecacerts");
if (!file.isFile())
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 " + requestUrl + ":" + port + "...");
SSLSocket socket = (SSLSocket) factory.createSocket(requestUrl, port);
socket.setSoTimeout(10000);
try
System.out.println("Starting SSL handshake...");
socket.startHandshake();
socket.close();
System.out.println("\\nNo 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("\\nServer sent " + chain.length + " certificate(s):\\n");
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 = requestUrl + "-" + (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 + "'");
/**
* 转为16进制
*
* @param bytes
* @return
*/
private static String toHexString(byte[] bytes)
StringBuilder sb = new StringBuilder(bytes.length * 3);
for (int b : bytes)
b &= 0xff;
sb.append(HEX_DIGITS[b >> 4]);
sb.append(HEX_DIGITS[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;
@Override
public X509Certificate[] getAcceptedIssuers()
throw new UnsupportedOperationException();
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throw new UnsupportedOperationException();
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
this.chain = chain;
tm.checkServerTrusted(chain, authType);
原因:服务端的证书没有被Java认证,所以导致请求失败
Java程序对受信证书的查找顺序:
-
javax.net.ssl.trustStore
就是 System.setProperty(“javax.net.ssl.trustStore”, “D:\\cacert.keystore”);
或者通过JVM参数指定:-Djavax.net.ssl.trustStore=D:\\cacert.keystore
-
%JAVA_HOME%\\jre\\lib\\security\\jssecacerts 【推荐】
默认没有jssecacerts,一般把cacerts复制成jssecacerts,然后再使用keytool来修改它。
jsse的全称是Java Secure Socket Extension。
-
%JAVA_HOME%\\jre\\lib\\security\\cacerts
通常情况下不建议通过-Djavax.net.ssl.trustStore=D:\\cacert.keystore来直接修改keystore文件的位置,因为这样会造成系统中其他模块可能找不到自己对应的证书了。
以上是关于Java# 请求https时证书不可信 PKIX SunCertPathBuilderException:unable to find valid certification....的主要内容,如果未能解决你的问题,请参考以下文章
Java生成证书工具类 InstallCert.java解决httpClient访问https出错:PKIX path building failed
如何使用 Java 在 https 连接请求中附加 .pfx 证书?
异常解决:sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.cer
SSLHandshakeException:PKIX 路径构建失败 SunCertPathBuilderException:无法找到请求目标的有效证书路径