解决 『SunCertPathBuilderException:unable to find valid certification path to requested target』 问题

解决 『SunCertPathBuilderException:unable to find valid certification path to requested target』 问题

★ 问题

在 maven 编译的时候,出现证书校验错误,部分log如下:

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

此问题通常是在访问maven依赖库的网站(https的)时,证书被替换了,然后导致的。
为什么证书会被替换?可能的原因是,代理服务器作为中间人,在https传输过程中,将服务器的证书替换了,然后就可以监听https的流量了。通常,公司里会这么干。这里代理服务器利用了https协议的密钥交换过程,可以参考这篇文章:扫盲 HTTPS 和 SSL/TLS 协议

解决此问题,有两种方法。

★ 方法1:为maven添加属性maven.wagon.http.ssl.insecure=true

在mvn命令后面加上-Dmaven.wagon.http.ssl.insecure=true。此属性是让maven忽略安全性,不再校验服务器的证书(此时服务器的证书可能是被替换的)。

mvn -Dmaven.wagon.http.ssl.insecure=true package

★ 方法2:将证书添加到 cacerts 中

环境:Windows。

cacerts包含了很多CA证书,位置在Java的安装目录: 『Java\jdk1.8.0_65\jre\lib\security\cacerts』。

执行如下命令,将证书加到cacerts中:

keytool.exe -importcert -file <新证书> -keystore Java\jdk1.8.0_65\jre\lib\security\cacerts -storepass changeit

<新证书>可以是cer格式的,例如,xxx.cer。

执行此命令会提示你是否信任此证书,输入yes,回车。然后证书就加入cacerts中了。部分log如下:

Trust this certificate? [no]:  yes
Certificate was added to keystore

◇ 关于cacerts的说明

参考: https://www.ibm.com/support/knowledgecenter/SSYKE2_8.0.0/com.ibm.java.security.component.80.doc/security-component/keytoolDocs/cacertsfile.html

A certificates file named “cacerts” resides in the security properties directory, java.home\lib\security, where java.home is the runtime environment directory (the jre directory in the SDK or the top-level directory of the Java™ 2 Runtime Environment).

The “cacerts” file represents a system-wide keystore with CA certificates. System administrators can configure and manage that file using keytool, specifying “jks” as the keystore type. The “cacerts” keystore file ships with several root CA certificates. The initial password of the “cacerts” keystore file is “changeit”. System administrators should change that password and the default access permission of that file when installing the SDK.

★ 参考

https://stackoverflow.com/questions/30480086/how-to-integrate-ssl-certificates-to-the-cacerts-file-in-jre-security-folder

你可能感兴趣的:(解决 『SunCertPathBuilderException:unable to find valid certification path to requested target』 问题)