我正在尝试使用twitter4j库为我的java项目发送推文。在我第一次运行时,我得到了关于证书sun.security.validator.ValidatorException
和sun.security.provider.certpath.SunCertPathBuilderException
的错误。然后我添加了twitter证书:
C:\Program Files\Java\jdk1.7.0_45\jre\lib\security>keytool -importcert -trustcacerts -file PathToCert -alias ca_alias -keystore "C:\Program Files\Java\jdk1.7.0_45\jre\lib\security\cacerts"
但没有成功。这是获得twitters的过程:
public static void main(String[] args) throws TwitterException {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("myConsumerKey")
.setOAuthConsumerSecret("myConsumerSecret")
.setOAuthAccessToken("myAccessToken")
.setOAuthAccessTokenSecret("myAccessTokenSecret");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
try {
Query query = new Query("iphone");
QueryResult result;
result = twitter.search(query);
System.out.println("Total amount of tweets: " + result.getTweets().size());
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("@" + tweet.getUser().getScreenName() + " : " + tweet.getText());
}
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
}
这是错误:
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=d35baff5 or
http://www.google.co.jp/search?q=1446302e
TwitterException{exceptionCode=[d35baff5-1446302e 43208640-747fd158 43208640-747fd158 43208640-747fd158], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.5}
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:177)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:81)
at twitter4j.TwitterImpl.get(TwitterImpl.java:1929)
at twitter4j.TwitterImpl.search(TwitterImpl.java:306)
at jku.cc.servlets.TweetsAnalyzer.main(TweetsAnalyzer.java:38)
Caused by: 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
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at twitter4j.internal.http.HttpResponseImpl.<init>(HttpResponseImpl.java:34)
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:141)
... 5 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
... 20 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
at java.security.cert.CertPathBuilder.build(Unknown Source)
... 26 more
Failed to search tweets: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
"more info" > "security" > "show certificate" > "details" > "export.."
。选择名称并选择文件类型example.cer。现在你有了keystore的文件,你必须将它添加到你的JVMC:\Program Files (x86)\Java\jre1.6.0_22\lib\security\cacerts.
example.cer
文件导入cacerts:keytool -import -alias example -keystore C:\Program Files (x86)\Java\jre1.6.0_22\lib\security\cacerts -file example.cer
系统会要求您输入密码,默认为changeit
重新启动JVM / PC。
来源:http://magicmonster.com/kb/prg/java/ssl/pkix_path_building_failed.html
这不是Twitter特定的答案,但这是您搜索此错误时出现的问题。如果您的系统在连接到在Web浏览器中查看时似乎具有有效证书的网站时收到此错误,则可能表示该网站的证书链不完整。
有关问题的简短摘要:证书颁发机构不使用其根证书来签署任何旧证书。相反,它们(通常)签署也设置了证书颁发机构标志的中间证书(即允许签署证书)。然后,当您从CA购买证书时,他们会使用其中一个中间证书对您的CSR进行签名。
您的Java信任存储很可能只有根证书,而不是中间证书。
配置错误的网站可能只返回其签名的证书。问题:它是使用不在您的信任库中的中间证书签名的。浏览器将通过下载或使用缓存的中间证书来处理此问题;这最大化了网站兼容性。但是,像OpenSSL这样的Java和工具却不会。这将导致问题中的错误。
您可以使用Qualys SSL Test来验证这种怀疑。如果你针对网站运行它,它说
此服务器的证书链不完整。
然后证实了这一点。您还可以通过查看认证路径并查看文本Extra Download来查看此信息。
如何解决:服务器管理员需要配置Web服务器以返回中间证书。例如,对于Comodo来说,这就是.ca-bundle
文件派上用场的地方。例如,在使用mod_ssl的Apache配置中,您将使用SSLCertificateChainFile
配置设置。对于nginx,您需要连接中间证书和签名证书,并在SSL证书配置中使用它。您可以通过在线搜索“不完整的证书链”找到更多信息。
我们得出以上错误的原因是JDK与许多可信证书颁发机构(CA)证书捆绑在一个名为'cacerts'的文件中,但是这个文件并不知道我们的自签名证书。换句话说,cacerts文件没有导入我们的自签名证书,因此不会将其视为可信实体,因此它会产生上述错误。
要解决上述错误,我们只需将自签名证书导入cacerts文件即可。
首先,找到cacerts文件。我们需要找出JDK的位置。如果您通过IDE之类的IDE或IntelliJ Idea运行应用程序,请转到项目设置并找出JDK位置。例如,在Mac OS上,cacerts文件的典型位置将位于Window的机器上的此位置/ Library / Java / JavaVirtualMachines / {{JDK_version}} / Contents / Home / jre / lib / security中,它位于{{Installation_directory}下} / {{JDK_version}} / JRE / LIB /安全
找到cacerts文件后,现在我们需要将自签名证书导入此cacerts文件。如果您不知道如何正确生成自签名证书,请查看上一篇文章。
如果您没有证书文件(.crt)并且只有.jks文件,则可以使用以下命令生成.crt文件。如果您已经有.crt / .pem文件,则可以忽略以下命令
##从密钥库生成证书(.jks文件)####
keytool -export -keystore keystore.jks -alias selfsigned -file selfsigned.crt
上面的步骤将生成一个名为selfsigned.crt.Now的文件,将证书导入cacerts
Now add the certificate to JRE/lib/security/cacerts (trustore)keytool -importcert -file selfsigned.crt -alias selfsigned -keystore {{cacerts path}}
例如
keytool -importcert -file selfsigned.nextgen.crt -alias selfsigned.nextgen -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/jre/lib/security/cacerts
这就是全部,重新启动您的应用程序,它应该工作正常。如果它仍然不起作用并获得SSL握手异常。这可能意味着您使用的是不同的域,然后在证书中注册。
链接with detailed explanation and step by step resolution is over here.
添加cacerts
不适合我。在启用带有标志-Djavax.net.debug=all
的日志之后,就开始了解来自jssecacerts
的java阅读。
导入jssecacerts
终于工作了。
我试图通过他们的更新站点在Eclipse中安装Cucumber-Eclipse插件时遇到了这个问题。我收到了相同的SunCertPathBuilderException错误:
Unable to read repository at http://cucumber.io/cucumber-eclipse/update-site/content.xml.
Unable to read repository at http://cucumber.io/cucumber-eclipse/update-site/content.xml.
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
虽然其他一些答案对于这个问题的具体情况是恰当和有用的,但它们对我的问题无益和误导。
就我而言,问题是为其更新站点提供的URL是:
但是,当通过浏览器导航到它时,它会重定向到(注意添加的“.github”):
所以解决方案是在eclipse中添加更新站点时简单地使用重定向版本的更新站点URL。
我遇到了同样的问题,并使用以下简单的步骤解决了这个问题:
1)从谷歌下载InstallCert.java
2)使用javac InstallCert.java编译它
3)使用带有主机名和https端口的java InstallCert.java运行InstallCert.java,并在请求输入时按“1”。它将“localhost”添加为可信密钥库,并生成名为“jssecacerts”的文件,如下所示:
java InstallCert localhost:443
4)将jssecacerts复制到$ JAVA_HOME / jre / lib / security文件夹中
解决这个问题的主要来源是:
https://ankurjain26.blogspot.in/2017/11/javaxnetsslsslhandshakeexception.html
通常,当可信证书的PATH不匹配时会发生这种异常。检查安全通信所需的此服务器证书的配置或路径。
我在ubuntu 15.10上遇到了同样的问题。请尝试在本地下载插件,例如https://github.com/lmenezes/elasticsearch-kopf/archive/master.zip并使用此命令安装:
sudo /usr/share/elasticsearch/bin/plugin install file:/home/dev/Downloads/elasticsearch-kopf-master.zip
路径可能因您的环境而异。
问候。
对我来说,证书错误突然出现,因为我在背景中运行小提琴手并且与证书混淆。它充当代理,如此接近并重启eclipse。
这是答案https://stackoverflow.com/a/36427118/1491414的补充。谢谢@MagGGG
我用以下方法解决了这个问题 -
经过几个小时尝试构建证书文件以使我的Java 6安装与新的twitter证书一起使用后,我终于偶然发现了一个非常简单的解决方案,其中包含了其中一个留言板的评论。只需从Java 7安装中复制cacerts文件,并覆盖Java 6安装中的文件。可能最好先备份cacerts文件,但是你只需要复制新的文件和BOOM!它只是工作。
请注意,我实际上将Windows cacerts文件复制到Linux安装上,它运行得很好。
该文件位于新旧Java jdk安装中的jre/lib/security/cacerts
中。
希望这可以拯救别人几个小时的恶化。
当您使用atlassian软件时遇到以上错误。 JIRA
2018-08-18 11:35:00,312 Caesium-1-4 WARN anonymous Default Mail Handler [c.a.mail.incoming.mailfetcherservice] Default Mail Handler[10001]: javax.mail.MessagingException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target while connecting to host 'imap.xyz.pl' as user '[email protected]' via protocol 'imaps, caused by: 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
您可以将证书添加到其可信密钥库(将missing_ca更改为正确的证书名称):
keytool -importcert -file missing_ca.crt -alias missing_ca -keystore /opt/atlassian/jira/jre/lib/security/cacerts
如果要求输入密码changeit
并确认y
之后只需重启jira。
如果您的存储库URL也适用于HTTP并且安全性不是问题,您可以转到settings.xml(通常但不总是位于%USERPROFILE%/.m2
中)并使用HTTP替换HTTPS以用于<repository>
和<pluginRepository>
URL。
例如,这个:
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>libs-release</name>
<url>https://<artifactory>/libs-release</url>
</repository>
应该替换为:
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>libs-release</name>
<url>https://<artifactory>/libs-release</url>
</repository>
通过arg -Djavax.net.ssl.trustStore=
我使用自己的信任商店而不是JRE
无论信任库中的证书是什么,我都收到此错误。对我来说,问题是arg行传递的属性的排序。当我在-Djavax.net.ssl.trustStore=
和-Djavax.net.ssl.trustStorePassword=
args之前放-Dspring.config.location=
和-jar
时,我能够通过https成功调用我的休息呼叫。
如果您正在使用CloudFoundry并遇到证书问题,那么您必须确保使用包含证书的密钥库服务再次推送jar。简单地取消绑定,绑定和重启将无效。
尝试复制java cacerts:
cp /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.172-9.b11.fc28.x86_64/jre/lib/security/cacerts $JAVA_HOME/jre/lib/security/cacerts
如果您在java应用程序尝试与另一个应用程序/站点通信时在linux容器中看到此问题,那是因为证书已错误地导入负载均衡器。导入证书需要遵循一系列步骤,如果操作不正确,您将看到类似的问题
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid
certification path to requested target
一旦正确导入证书,就应该完成。无需修改任何JDK证书。
这是一个解决方案,但我的故事形式有这个问题:
我几乎死了尝试上面给出的所有解决方案(3天),没有任何对我有用。
我失去了所有希望。
我联系了我的安全团队,因为我是代理人,他们告诉他们最近更新了他们的安全策略。
我没有通知开发人员,因此严厉责骂他们。
后来他们发布了一个新的“cacerts”文件,其中包含所有证书。
我删除了%JAVA_HOME%/ jre / lib / security中存在的cacerts文件,它解决了我的问题。
因此,如果您遇到此问题,可能来自您的网络团队也是这样的。
目标:
怎么做:
我的Keystore包装文件:
public class CertificateManager {
private final static Logger logger = Logger.getLogger(CertificateManager.class);
private String keyStoreLocation;
private String keyStorePassword;
private X509TrustManager myTrustManager;
private static KeyStore myTrustStore;
public CertificateManager(String keyStoreLocation, String keyStorePassword) throws Exception {
this.keyStoreLocation = keyStoreLocation;
this.keyStorePassword = keyStorePassword;
myTrustStore = createKeyStore(keyStoreLocation, keyStorePassword);
}
public void addCustomCertificate(String certFileName, String certificateAlias)
throws Exception {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init((KeyStore) null);
Certificate certificate = myTrustStore.getCertificate(certificateAlias);
if (certificate == null) {
logger.info("Certificate not exists");
addCertificate(certFileName, certificateAlias);
} else {
logger.info("Certificate exists");
}
tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(myTrustStore);
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
setMytrustManager((X509TrustManager) tm);
logger.info("Trust manager found");
break;
}
}
}
private InputStream fullStream(String fname) throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
InputStream resource = classLoader.getResourceAsStream(fname);
try {
if (resource != null) {
DataInputStream dis = new DataInputStream(resource);
byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
return new ByteArrayInputStream(bytes);
} else {
logger.info("resource not found");
}
} catch (Exception e) {
logger.error("exception in certificate fetching as resource", e);
}
return null;
}
public static KeyStore createKeyStore(String keystore, String pass) throws Exception {
try {
InputStream in = CertificateManager.class.getClass().getResourceAsStream(keystore);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(in, pass.toCharArray());
logger.info("Keystore was created from resource file");
return keyStore;
} catch (Exception e) {
logger.info("Fail to create keystore from resource file");
}
File file = new File(keystore);
KeyStore keyStore = KeyStore.getInstance("JKS");
if (file.exists()) {
keyStore.load(new FileInputStream(file), pass.toCharArray());
logger.info("Default keystore loaded");
} else {
keyStore.load(null, null);
keyStore.store(new FileOutputStream(file), pass.toCharArray());
logger.info("New keystore created");
}
return keyStore;
}
private void addCertificate(String certFileName, String certificateAlias) throws CertificateException,
IOException, KeyStoreException, NoSuchAlgorithmException {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream certStream = fullStream(certFileName);
Certificate certs = cf.generateCertificate(certStream);
myTrustStore.setCertificateEntry(certificateAlias, certs);
FileOutputStream out = new FileOutputStream(getKeyStoreLocation());
myTrustStore.store(out, getKeyStorePassword().toCharArray());
out.close();
logger.info("Certificate pushed");
}
public String getKeyStoreLocation() {
return keyStoreLocation;
}
public String getKeyStorePassword() {
return keyStorePassword;
}
public X509TrustManager getMytrustManager() {
return myTrustManager;
}
public void setMytrustManager(X509TrustManager myTrustManager) {
this.myTrustManager = myTrustManager;
}
}
如有必要,此类将创建密钥库,并且可以管理其中的证书。现在是SSL上下文的类:
public class CustomTrustManager implements X509TrustManager {
private final static Logger logger = Logger.getLogger(CertificateManager.class);
private static SSLSocketFactory socketFactory;
private static CustomTrustManager instance = new CustomTrustManager();
private static List<CertificateManager> register = new ArrayList<>();
public static CustomTrustManager getInstance() {
return instance;
}
private X509TrustManager defaultTm;
public void register(CertificateManager certificateManager) {
for(CertificateManager manager : register) {
if(manager == certificateManager) {
logger.info("Certificate manager already registered");
return;
}
}
register.add(certificateManager);
logger.info("New Certificate manager registered");
}
private CustomTrustManager() {
try {
String algorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
tmf.init((KeyStore) null);
boolean found = false;
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
defaultTm = (X509TrustManager) tm;
found = true;
break;
}
}
if(found) {
logger.info("Default trust manager found");
} else {
logger.warn("Default trust manager was not found");
}
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{this}, null);
SSLContext.setDefault(sslContext);
socketFactory = sslContext.getSocketFactory();
HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
logger.info("Custom trust manager was set");
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
logger.warn("Custom trust manager can't be set");
e.printStackTrace();
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
List<X509Certificate> out = new ArrayList<>();
if (defaultTm != null) {
out.addAll(Arrays.asList(defaultTm.getAcceptedIssuers()));
}
int defaultCount = out.size();
logger.info("Default trust manager contain " + defaultCount + " certficates");
for(CertificateManager manager : register) {
X509TrustManager customTrustManager = manager.getMytrustManager();
X509Certificate[] issuers = customTrustManager.getAcceptedIssuers();
out.addAll(Arrays.asList(issuers));
}
logger.info("Custom trust managers contain " + (out.size() - defaultCount) + " certficates");
X509Certificate[] arrayOut = new X509Certificate[out.size()];
return out.toArray(arrayOut);
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
for(CertificateManager certificateManager : register) {
X509TrustManager customTrustManager = certificateManager.getMytrustManager();
try {
customTrustManager.checkServerTrusted(chain, authType);
logger.info("Certificate chain (server) was aproved by custom trust manager");
return;
} catch (Exception e) {
}
}
if (defaultTm != null) {
defaultTm.checkServerTrusted(chain, authType);
logger.info("Certificate chain (server) was aproved by default trust manager");
} else {
logger.info("Certificate chain (server) was rejected");
throw new CertificateException("Can't check server trusted certificate.");
}
}
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
try {
if (defaultTm != null) {
defaultTm.checkClientTrusted(chain, authType);
logger.info("Certificate chain (client) was aproved by default trust manager");
} else {
throw new NullPointerException();
}
} catch (Exception e) {
for(CertificateManager certificateManager : register) {
X509TrustManager customTrustManager = certificateManager.getMytrustManager();
try {
customTrustManager.checkClientTrusted(chain, authType);
logger.info("Certificate chain (client) was aproved by custom trust manager");
return;
} catch (Exception e1) {
}
}
logger.info("Certificate chain (client) was rejected");
throw new CertificateException("Can't check client trusted certificate.");
}
}
public SSLSocketFactory getSocketFactory() {
return socketFactory;
}
}
此类作为单例生成,因为只允许一个defaultSSL上下文。那么,现在用法:
CertificateManager certificateManager = new CertificateManager("C:\\myapplication\\mykeystore.jks", "changeit");
String certificatePath = "C:\\myapplication\\public_key_for_your_ssl_service.crt";
try {
certificateManager.addCustomCertificate(certificatePath, "alias_for_public_key_for_your_ssl_service");
} catch (Exception e) {
log.error("Can't add custom certificate");
e.printStackTrace();
}
CustomTrustManager.getInstance().register(certificateManager);
可能,它不适用于此设置,因为我将证书文件保存在资源文件夹中,所以我的路径不是绝对的。但一般来说,它完美地运作。
如果您的主机位于防火墙/代理后面,请在cmd中使用以下命令:
keytool -J-Dhttps.proxyHost=<proxy_hostname> -J-Dhttps.proxyPort=<proxy_port> -printcert -rfc -sslserver <remote_host_name:remote_ssl_port>
将<proxy_hostname>
和<proxy_port>
替换为配置的HTTP代理服务器。将<remote_host_name:remote_ssl_port>
替换为远程主机(基本上是url)和具有认证问题的端口之一。
获取打印的最后一个证书内容并将其复制(同时复制开始和结束证书)。将其粘贴到文本文件中,并为其指定.crt扩展名。现在使用java keytool命令将此证书导入cacerts,它应该可以工作。
keytool -importcert -file <filename>.crt -alias randomaliasname -keystore %JAVA_HOME%/jre/lib/security/cacerts -storepass changeit
下载cert文件,并使用证书文件更新密钥库,如下面的命令所示。
sudo keytool -importcert -alias“aws2”-file~ / Desktop / * aws.crt -keystore /Library/java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/security/cacerts
我偶然发现了这个需要花费数小时研究才能修复的问题,特别是使用自动生成的证书,这与官方证书不同,它们非常棘手,而Java并不那么喜欢它们。
请检查以下链接:Solve Problem with certificates in Java
基本上,您必须将证书从服务器添加到Java Home证书。
InstallCert
的Java源代码并在服务器运行时执行它,提供以下参数server[:port]
。不需要密码,因为原始密码适用于Java证书(“changeit”)。jssecerts
文件(如果从Eclipse执行,请确保配置Run -> Configurations
的工作目录)。$JAVA_HOME/jre/lib/security
执行这些步骤后,与证书的连接将不再在Java中生成异常。
以下源代码很重要,它从(Sun)Oracle博客中消失,我发现它唯一的页面是在提供的链接上,因此我将其附在答案中以供参考。
/*
* 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.
*/
/**
* Originally from:
* http://blogs.sun.com/andreas/resource/InstallCert.java
* Use:
* java InstallCert hostname
* Example:
*% java InstallCert ecc.fedora.redhat.com
*/
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;
/**
* Class used to add the server's certificate to the KeyStore
* with your trusted certificates.
*/
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 [: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);
}
}
}
我的UI方法:
CMD线:
当我的系统上存在JDK和JRE 1.8.0_112时,情况略有不同。
我使用已知的命令将新CA证书导入[JDK_FOLDER]\jre\lib\security\cacerts
:
keytool -import -trustcacerts -keystore cacerts -alias <new_ca_alias> -file <path_to_ca_cert_file>
尽管如此,我仍然保持相同的PKIX路径构建失败错误。
我使用java -Djavax.net.debug=all ... > debug.log
将调试信息添加到java CLI。在debug.log文件中,以trustStore开头的行是:实际指向[JRE_FOLDER]\lib\security\cacerts
中的cacerts存储。
在我的情况下,解决方案是将JDK(添加了新CA)使用的cacerts文件复制到JRE使用的文件上并修复了问题。
尝试在浏览器中加载目标URL并查看站点的证书(通常可以通过带有锁定符号的图标访问它。它位于浏览器地址栏的左侧或右侧)是否由于其他原因而过期或不受信任。
新版本通常附带更新的可信证书集。
如果可能的话,卸载旧版本。这将使错误配置错误显而易见。
如果您使用JDK以外的最新版本进行开发 - 尝试用最新安装的JRE替换%JAVA_HOME%/jre/lib/security/cacerts
文件(首先制作备份副本),如@ jeremy-goodell在他的answer中建议的那样
如果以上没有解决您的问题,请使用keytool
将证书保存到Java的密钥库:
keytool -trustcacerts -keystore "%JAVA_HOME%jre\lib\security\cacerts" -storepass changeit -importcert -alias <alias_name> -file <path_to_crt_file>
带有证书的文件可以从@MagGGG在他的answer中建议的浏览器中获得。
注意1:您可能需要对链中的每个证书重复此操作,以获取您站点的证书。从根目录开始。
注2:<alias_name>
在商店的钥匙中应该是唯一的,否则keytool
会显示错误。
要获取商店中所有证书的列表,您可以运行:
keytool -list -trustcacerts -keystore "%JAVA_HOME%jre\lib\security\cacerts" -storepass changeit
如果出现问题,这将有助于您从商店中删除证书:
keytool -delete -alias <alias_name> -keystore "%JAVA_HOME%jre\lib\security\cacerts" -storepass changeit
-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true
它用于跳转证书验证。
我想为smtp.gmail.com导入证书
只有解决方案适用于我1.输入命令查看此证书
D:\ openssl \ bin \ openssl.exe s_client -connect smtp.gmail.com:465
现在运行命令,你很高兴
问题背景:
当我尝试在我的项目中运行mvn clean install并通过Netbeans IDE clean和build选项时,我遇到了以下错误。此问题是由于我们通过NET beans IDE /通过命令提示符下载时无法使用证书,但能够通过浏览器下载文件。
错误:
Caused by: org.eclipse.aether.transfer.ArtifactTransferException: Could not transfer artifact com.java.project:product:jar:1.0.32 from/to repo-local (https://url/local-repo): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
解析度:
1.下载相关网址的证书:
2.现在安装密钥库以解决问题。
C:\ Program Files \ Java \ jdk1.8.0_141 \ jre \ bin> keytool -importcert -file“C:/user/sheldon/desktop/product.cer”-alias product -keystore“C:/ Program Files / Java / jdk1.8.0_141 / JRE / lib / security中/ cacerts中”。
示例命令行命令/输出:
keytool -importcert -file "C:/Users/sheldon/Desktop/product.cer" -alias product -keystore "C:/Program iles/Java/jdk1.8.0_141/jre/lib/security/cacerts"
Enter keystore password:
Trust this certificate? [no]: yes
Certificate was added to keystore