Java:sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径

时间:2011-08-02 08:04:30

标签: java ssl https ssl-certificate

我有一个类将从 https 服务器下载文件。当我运行它时,它会返回很多错误。我的证书似乎有问题。是否可以忽略客户端 - 服务器身份验证?如果是这样,怎么样?

package com.da;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.Future;

import org.apache.http.HttpResponse;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.HttpAsyncClient;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.nio.client.methods.HttpAsyncGet;
import org.apache.http.nio.client.methods.HttpAsyncPost;

public class RSDDownloadFile {
    static FileOutputStream fos;

    public void DownloadFile(String URI, String Request) throws Exception
    {
        java.net.URI uri = URIUtils.createURI("https", "176.66.3.69:6443", -1, "download.aspx",
                "Lang=EN&AuthToken=package", null);
        System.out.println("URI Query: " + uri.toString());

        HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
        httpclient.start();
        try {
            Future<Boolean> future = httpclient.execute(
                    new HttpAsyncGet(uri),
                    new ResponseCallback(), null);

            Boolean result = future.get();
            if (result != null && result.booleanValue()) {
                System.out.println("\nRequest successfully executed");
            } else {
                System.out.println("Request failed");
            }              
        } 
        catch(Exception e){
            System.out.println("[DownloadFile] Exception: " + e.getMessage());
        }
        finally {
            System.out.println("Shutting down");
            httpclient.shutdown();
        }
        System.out.println("Done");  

    }

    static class ResponseCallback extends AsyncCharConsumer<Boolean> {

        @Override
        protected void onResponseReceived(final HttpResponse response) {
             System.out.println("Response: " + response.getStatusLine());
             System.out.println("Header: " + response.toString());
             try {   
                 //if(response.getStatusLine().getStatusCode()==200)
                     fos = new FileOutputStream( "Response.html" );
             }catch(Exception e){
                 System.out.println("[onResponseReceived] Exception: " + e.getMessage());
             }
        }

        @Override
        protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException {
            try
            {
                while (buf.hasRemaining()) 
                {
                    //System.out.print(buf.get());
                    fos.write(buf.get());
                }
            }catch(Exception e)
            {
                System.out.println("[onCharReceived] Exception: " + e.getMessage());
            }
        }

        @Override
        protected void onCleanup() {
            try
            {             
                if(fos!=null)
                    fos.close();
            }catch(Exception e){
                System.out.println("[onCleanup] Exception: " + e.getMessage());         
            }
             System.out.println("onCleanup()");
        }

        @Override
        protected Boolean buildResult() {
            return Boolean.TRUE;
        }

    }
}

错误:

URI Query: https://176.66.3.69:6443/download.aspx?Lang=EN&AuthToken=package
Aug 2, 2011 3:47:57 PM org.apache.http.impl.nio.client.NHttpClientProtocolHandler exception
SEVERE: I/O error: General SSLEngine problem
javax.net.ssl.SSLHandshakeException: General SSLEngine problem
    at com.sun.net.ssl.internal.ssl.Handshaker.checkThrown(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLEngineImpl.checkTaskThrown(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLEngineImpl.writeAppRecord(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLEngineImpl.wrap(Unknown Source)
    at javax.net.ssl.SSLEngine.wrap(Unknown Source)
    at org.apache.http.impl.nio.reactor.SSLIOSession.doHandshake(SSLIOSession.java:154)
    at org.apache.http.impl.nio.reactor.SSLIOSession.isAppInputReady(SSLIOSession.java:276)
    at org.apache.http.impl.nio.client.InternalClientEventDispatch.inputReady(InternalClientEventDispatch.java:79)
    at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:161)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:335)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:315)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:275)
    at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104)
    at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:542)
    at java.lang.Thread.run(Unknown Source)
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLEngineImpl.fatal(Unknown Source)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
    at com.sun.net.ssl.internal.ssl.Handshaker$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.net.ssl.internal.ssl.Handshaker$DelegatedTask.run(Unknown Source)
    at org.apache.http.impl.nio.reactor.SSLIOSession.doHandshake(SSLIOSession.java:180)
    ... 9 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 com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(Unknown Source)
    ... 16 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)
    ... 21 more
onCleanup()

[DownloadFile] Exception: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
Shutting down
Done

26 个答案:

答案 0 :(得分:181)

当您的服务器具有自签名证书时,会出现此问题。要解决此问题,您可以将此证书添加到JVM的受信任证书列表中。

In this article作者介绍了如何从浏览器中获取证书并将其添加到JVM的cacerts文件中。您可以编辑JAVA_HOME/jre/lib/security/cacerts文件或使用-Djavax.net.ssl.trustStore参数运行您的应用程序。验证您正在使用哪个JDK / JRE,因为这通常会引起混淆。

另请参阅:How are SSL certificate server names resolved/Can I add alternative names using keytool?如果您遇到java.security.cert.CertificateException: No name matching localhost found例外。

答案 1 :(得分:127)

这是macOS上可靠的功能。确保将example.com和443替换为您尝试连接的实际主机名和端口,并提供自定义别名。第一个命令从远程服务器下载提供的证书,并以x509格式在本地保存。第二个命令将保存的证书加载到Java的SSL信任库中。

openssl x509 -in <(openssl s_client -connect example.com:443 -prexit 2>/dev/null) -out ~/example.crt
sudo keytool -importcert -file ~/example.crt -alias example -keystore $(/usr/libexec/java_home)/jre/lib/security/cacerts -storepass changeit

答案 2 :(得分:40)

我遇到了来自赛门铁克的有效签名通配符证书的相同问题。

首先尝试使用 -Djavax.net.debug = SSL 运行您的Java应用程序,以查看实际情况。

我最终 导入中间证书 ,导致证书链中断。

我从赛门铁克下载了缺少的中间证书(在我的情况下,您可以在ssl握手日志中看到缺少证书的下载链接:http://svrintl-g3-aia.verisign.com/SVRIntlG3.cer。)

我在java密钥库中导入了cert。导入中间证书后,我的通配符ssl证书终于开始工作了:

keytool -import -keystore ../jre/lib/security/cacerts -trustcacerts -alias "VeriSign Class 3 International Server CA - G3" -file /pathto/SVRIntlG3.cer

答案 3 :(得分:34)

  1. 使用Firefox导出SSL证书。您可以通过在浏览器中点击URL导出它,然后选择导出证书的选项。我们假设证书文件名是 your.ssl.server.name.crt
  2. 转到JRE_HOME/binJDK/JRE/bin
  3. 输入命令
  4. keytool -keystore ..\lib\security\cacerts -import -alias your.ssl.server.name -file .\relative-path-to-cert-file\your.ssl.server.name.crt
  5. 重新启动Java进程

答案 4 :(得分:17)

@Gabe Martin-Dempesy的回答对我有帮助。我写了一个与之相关的小脚本。用法非常简单。

从主机安装证书:

#include <iostream>
#include <pthread.h>

using namespace std;

class A{
  public:
    static void* thread(void* args);
    int parella_thread(int thread_num);
};

void* A::thread(void* args)
{
  cout<<"hello world"<<endl;
}

int A::parella_thread(int thread_num)
{
  pthread_t* thread_ids = new pthread_t[thread_num];
  for(int i=0;i<thread_num;i++)
  {
    pthread_create(&thread_ids[i],NULL,thread,(void*)NULL);
  }
  delete[] thread_ids;
}

int main(int argc,char*argv[])
{
  A test;
  test.parella_thread(4);
  return 0; 
}

删除已安装的证书。

> sudo ./java-cert-importer.sh example.com

<强> java-cert-importer.sh

> sudo ./java-cert-importer.sh example.com --delete

答案 5 :(得分:17)

引自No more 'unable to find valid certification path to requested target'

  

尝试使用JSSE打开与主机的SSL连接时。这通常意味着服务器正在使用测试证书(可能使用keytool生成)而不是来自知名商业证书颁发机构(如Verisign或GoDaddy)的证书。在这种情况下,Web浏览器会显示警告对话框,但由于JSSE无法假定交互式用户存在,因此默认情况下会抛出异常。

     

证书验证是SSL安全性的一个非常重要的部分,但我不是在编写此条目来解释详细信息。如果您有兴趣,可以先阅读Wikipedia blurb。我正在编写此条目,以显示一种与测试证书通信的简单方法,如果您真的想这样做。

     

基本上,您希望将服务器的证书添加到具有可信证书的KeyStore

尝试那里提供的代码。这可能有所帮助。

答案 6 :(得分:5)

我能够让它只使用代码,即不需要使用keytool:

import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.nio.conn.NoopIOSessionStrategy;
import org.apache.http.nio.conn.SchemeIOSessionStrategy;
import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class Test
{
    private static final DynamicIntProperty MAX_TOTAL_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
    private static final DynamicIntProperty ROUTE_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
    private static final DynamicIntProperty CONNECT_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connect.timeout", 60000);
    private static final DynamicIntProperty SOCKET_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.socket.timeout", -1);
    private static final DynamicIntProperty CONNECTION_REQUEST_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connectionrequest.timeout", 60000);
    private static final DynamicBooleanProperty STALE_CONNECTION_CHECK = DynamicPropertyFactory.getInstance().getBooleanProperty("X.checkconnection", true);

    public static void main(String[] args) throws Exception
    {

        SSLContext sslcontext = SSLContexts.custom()
                .useTLS()
                .loadTrustMaterial(null, new TrustStrategy()
                {
                    @Override
                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException
                    {
                        return true;
                    }
                })
                .build();
        SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new AllowAll());

        Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create()
                .register("http", NoopIOSessionStrategy.INSTANCE)
                .register("https", sslSessionStrategy)
                .build();

        DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT);
        PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor, sessionStrategyRegistry);
        connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS.get());
        connectionManager.setDefaultMaxPerRoute(ROUTE_CONNECTIONS.get());

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(SOCKET_TIMEOUT.get())
                .setConnectTimeout(CONNECT_TIMEOUT.get())
                .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT.get())
                .setStaleConnectionCheckEnabled(STALE_CONNECTION_CHECK.get())
                .build();

        CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom()
                .setSSLStrategy(sslSessionStrategy)
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig)
                .build();

        httpClient.start();

        // use httpClient...
    }

    private static class AllowAll implements X509HostnameVerifier
    {
        @Override
        public void verify(String s, SSLSocket sslSocket) throws IOException
        {}

        @Override
        public void verify(String s, X509Certificate x509Certificate) throws SSLException {}

        @Override
        public void verify(String s, String[] strings, String[] strings2) throws SSLException
        {}

        @Override
        public boolean verify(String s, SSLSession sslSession)
        {
            return true;
        }
    }
}

答案 7 :(得分:5)

我的Apache 2.4实例上的此错误的来源(使用Comodo通配符证书)是SHA-1签名根证书的不完整路径。颁发的证书中有多个链,导致SHA-1根证书的链缺少intermediate certificate。现代浏览器知道如何处理这个问题,但Java 7默认不处理它(尽管在代码中有一些复杂的方法可以解决这个问题)。结果是看起来与自签名证书的情况相同的错误消息:

Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
    ... 22 more

在这种情况下,由于缺少中间证书,正在生成“无法找到所请求目标的有效证书路径”消息。您可以使用针对服务器的SSL Labs测试来检查缺少哪个证书。找到相应的证书后,下载它(如果服务器在您的控制之下),将其添加到证书包中。或者,您可以在本地导入缺少的证书。在服务器上容纳此问题是解决该问题的更通用的解决方案。

答案 8 :(得分:4)

对于那些喜欢Debian和预先打包的Java的人:

sudo mkdir /usr/share/ca-certificates/test/  # don't mess with other certs
sudo cp ~/tmp/test.loc.crt /usr/share/ca-certificates/test/
sudo dpkg-reconfigure --force ca-certificates  # check your cert in curses GUI!
sudo update-ca-certificates --fresh --verbose

不要忘记检查/etc/default/cacerts

# enable/disable updates of the keystore /etc/ssl/certs/java/cacerts
cacerts_updates=yes

删除证书:

sudo rm /usr/share/ca-certificates/test/test.loc.crt
sudo rm /etc/ssl/certs/java/cacerts
sudo update-ca-certificates --fresh --verbose

答案 9 :(得分:4)

仅适用于Windows,请按以下步骤操作:

  1. 在Chrome中转到设置。
  2. 在“设置”中,单击“显示高级设置
  3. 在HTTPS / SSL下单击“管理证书”。
  4. 导出您的证书。
  5. 在Windows搜索中(按键盘上的Windows键)输入java。
  6. 选择(配置Java)选项将打开Java控制面板
  7. 在“Java控制面板”中选择“安全”选项卡
  8. 选择管理证书
  9. 点击导入
  10. 在(用户)选项卡下选择,证书类型为(可信证书)
  11. 点击导入按钮,浏览下载的证书并导入。

答案 10 :(得分:2)

更新:重启帮助很巧合(我希望如此,万岁!)。问题的真正原因是:当指示Gradle使用特定密钥库时,该密钥库还必须包含所有官方根证书。否则,它无法从常规存储库访问库。我必须做的是:

导入自签名证书:

keytool -import -trustcacerts -alias myselfsignedcert -file /Users/me/Desktop/selfsignedcert.crt -keystore ./privateKeystore.jks

添加官方根证书:

keytool -importkeystore -srckeystore <java-home>/lib/security/cacerts -destkeystore ./privateKeystore.jks

也许Gradle守护程序也妨碍了。如果事情开始变得黯淡,可能值得杀死./gradlew --status找到的所有正在运行的守护进程。

原始发布:

我知道,没有人会相信这一点。不过,如果一切都失败了,试一试: 在我的Mac 重新启动后,问题就消失了。哎呀。

背景: ./gradlew jar一直给我&#34;找不到要求目标的有效证书路径&#34;

我遇到了一个自签名证书,从浏览器保存,导入privateKeystore.jks。然后指示Gradle使用privateKeystore.jks:

org.gradle.jvmargs=-Djavax.net.debug=SSL -Djavax.net.ssl.trustStore="/Users/me/IntelliJ/myproject/privateKeystore.jks"  -Djavax.net.ssl.trustStorePassword=changeit

如上所述,这仅在重启后才有效。

答案 11 :(得分:2)

有很多方法可以解决这个问题...

一种方法是在密钥库文件中设置TrustStore证书,并将其放在应用程序的路径中,然后在main方法中设置以下系统属性:

{
  "name": "boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "input.js",
  "scripts": {
    "serve": "live-server public",
    "build": "babel src/index.js --out-file public/scripts/bundle.js --presets env --watch"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "live-server": "^1.2.1"
  }
}

另一种方法是将密钥库作为资源文件放置在项目jar文件中并加载:

public static void main(String[] args) {
  System.setProperty("javax.net.ssl.trustStore", "trust-store.jks");
  System.setProperty("javax.net.ssl.trustStorePassword", "TrustStore");
  ...
}

在Windows中,您也可以尝试以下解决方案:https://stackoverflow.com/a/59056537/980442


我以这种方式从证书颁发机构CA public static SSLContext createSSLContext(String resourcePath, String pass) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException, KeyManagementException { // initialise the keystore final char[] password = pass.toCharArray(); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(ThisClass.class.getResourceAsStream(resourcePath ), password); // Setup the key manager factory. KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, password); // Setup the trust manager factory. TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); SSLContext sslc = SSLContext.getInstance("TLS"); sslc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); return sslc; } public static void main(String[] args) { SSLContext.setDefault( createSSLContext("/trust-store.jks", "TrustStore")); ... } 文件创建了密钥库文件:

.crt

仅供参考:https://docs.oracle.com/javadb/10.8.3.0/adminguide/cadminsslclient.html

答案 12 :(得分:2)

AVG版本18.1.3044(使用Windows 10)干扰了我的本地Spring应用程序。

解决方案:输入名为“网络和电子邮件”的AVG部分并停用“电子邮件保护”。 如果站点不安全,AVG会阻止证书。

答案 13 :(得分:2)

使用带有使用SHA2签名的Java 7的GoDaddy证书也可能导致这种情况。

Chrome和所有其他浏览器都开始弃用使用SHA1签名的SSL证书,因为它不够安全。

更多信息on the issue can be found here,以及如果您现在需要在服务器上解决此问题。

答案 14 :(得分:1)

您有两个选择,将自签名证书导入到软件运行的每个jvm的java密钥库中,或者尝试非验证的ssl工厂:

jdbc:postgresql://myserver.com:5432/mydatabasename?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory

答案 15 :(得分:1)

我遇到了与证书错误相同的问题,因为SNI,我使用的http客户端没有实现SNI。因此版本更新完成了工作

   <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.6</version>
    </dependency>

答案 16 :(得分:1)

出现了类似此图像的问题。

enter image description here

尝试了一些解决方案。 但是发现即使是同一个项目,当它在另一个人的工作场所时,也完全可以。无需其他设置。因此,我们猜测这是一个环境问题。我们尝试更改JDK版本,IDE,但是没有用。我们花了大约4个小时进行调查,直到我们尝试了评分最高的答案。我没有找到该答案中提到的错误,但通过浏览器发现有关HTTP URL(锁)的信息,我得到了Charles的认证。然后我意识到我的查尔斯一直在忙。只要我关闭它,它就可以正常工作。

所以我留下的经验可能对您的情况有所帮助。

答案 17 :(得分:1)

我遵循的简单步骤。

问题: 我试图使用一个简单的Java类(main)连接到端点(https://%s.blob.core.windows.net)方法)。

因此,我遇到了如上所述的认证问题。

解决方案:

  1. 使用浏览器(chrome)获取证书。为此,将端点URL粘贴到浏览器中并输入。现在,您将看到一个锁形图标,单击该->证书->详细信息->复制到文件->下载。

  2. 以管理员身份打开cmd(我正在使用Windows),然后导航到您下载.cer文件的目录。

3.(可选)如果在同一台计算机上使用多个JDK,则将JDK版本更改为与在应用程序中使用的版本相同。

  1. 现在使用以下命令

keytool-导入-alias mycertificate -keystore“ C:\ Program Files \ Java \ jdk-11.0.5 \ lib \ security \ cacerts“-文件myurlcrt.cer

  1. 提供默认密码: changeit

  2. 信任此证书:是

您完成了。

谢谢!

答案 18 :(得分:0)

这解决了我的问题,

我们需要将证书导入本地Java。如果没有,我们可以得到以下异常。

    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(Alerts.java:192)
        at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)

SSLPOKE是一个工具,您可以在其中测试本地计算机上的https连接。

用于测试连接性的命令:

"%JAVA_HOME%/bin/java" SSLPoke <hostname> 443
    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(PKIXValidator.java:387)
        at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
        at sun.security.validator.Validator.validate(Validator.java:260)
        at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
        at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
        at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
        at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1496)
        at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
        at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
        at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
        at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:747)
        at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
        at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:138)
        at SSLPoke.main(SSLPoke.java:31)
    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to 
    requested target
        at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
        at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
        at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
        at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
        ... 15 more
keytool -import -alias brinternal -keystore "%JAVA_HOME%/jre/lib/security/cacerts" -file <cert path>

这将首先提示输入“输入密钥库密码:” changeit是默认密码。最后提示“是否信任此证书?[no]:”,请提供“是”以将证书添加到密钥库中。

验证:

C:\tools>"%JAVA_HOME%/bin/java" SSLPoke <hostname> 443
Successfully connected    

答案 19 :(得分:0)

就我而言,我正在使用Java 1.6运行MacOs High Sierra。该cacert文件与上面Gabe Martin-Dempesy的答案中所引用的位置不同。该cacert文件也已经链接到另一个位置(/ Library / Internet插件/JavaAppletPlugin.plugin/Contents/Home/lib/security/cacerts)。

使用FireFox,我将证书从有问题的网站导出到了名为“ exportedCertFile.crt”的本地文件中。从那里,我使用keytool将证书移到cacert文件中。这解决了问题。

bash-3.2# cd /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/security/
bash-3.2# keytool -importcert -file ~/exportedCertFile.crt -alias example -keystore cacerts -storepass changeit

答案 20 :(得分:0)

首先下载ssl证书,然后您可以转到Java bin路径,在控制台中执行以下命令。

C:\java\JDK1.8.0_66-X64\bin>keytool -printcert -file C:\Users\lova\openapi.cer -keystore openapistore

答案 21 :(得分:0)

确保https://176.66.3.69:6443/具有有效的证书。 您可以首先通过浏览器检查它https not secure,如果它可以在浏览器中运行,它将在Java中运行。

对我有用

答案 22 :(得分:0)

就我而言,我的密钥库和信任库都具有相同的证书,因此删除信任库会有所帮助。如果您有多个证书副本,有时证书链可能会成为问题。

答案 23 :(得分:0)

原来的问题是 - 如何忽略证书错误,这里是使用 SpringBoot 和 RestTemplate 的解决方案

@Service
public class SomeService {

    private final RestTemplate restTemplate;

    private final ObjectMapper objectMapper;    

    private static HttpComponentsClientHttpRequestFactory createRequestFactory() {
        try {
            SSLContextBuilder sslContext = new SSLContextBuilder();
            sslContext.loadTrustMaterial(null, new TrustAllStrategy());
            CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext.build()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
            requestFactory.setHttpClient(client);
            return requestFactory;
        } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException var3) {
            throw new IllegalStateException("Couldn't create HTTP Request factory ignore SSL cert validity: ", var3);
        }
    }

    @Autowired
    public SomeService(RestTemplate restTemplate, ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
        this.dimetorURL = dimetorURL;
        restTemplate.setRequestFactory(createRequestFactory());
    }


    public ResponseEntity<ResponseObject> sendRequest(RequestObject requestObject) {
        //...
        return restTemplate.exchange(url, HttpMethod.GET, ResponseObject.class);
        //...
    }
}

答案 24 :(得分:0)

如果在 maven 或 maven with TestNG 中遇到此错误:

  1. 从目标网站下载证书并在您的机器上安装证书(使用上面建议的 keytool,或在 Windows 上)
  2. 将以下内容添加到 maven 参数(命令行和/或 IDE): -Djavax.net.ssl.trustStore=C:\Users\me.keystore -Djavax.net.ssl.trustStorePassword=X 其中 X 是您在 keytool 步骤中使用的密码。

注意:C:\Users\me.keystore 也应设置为与您的机器匹配。 例如:

mvn -ea -Dtestng.dtd.http=true  -Djavax.net.ssl.trustStore=C:\Users\me\.keystore -Djavax.net.ssl.trustStorePassword=X -Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true -Dcucumber.features=src/test/resources -Dcucumber.glue=com.myapp -Dcucumber.filter.tags="@MY_TEST"

答案 25 :(得分:-6)

遇到此问题时,我只需将android studio zip提取到相同的旧文件夹中即可解决问题