1. 程式人生 > 其它 >maven配置下載包 解決SunCertPathBuilderException:unable to find valid certification path to requested target

maven配置下載包 解決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