Java 建立 SSL 连接时 PKIX 路径构建失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2290570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:43:46  来源:igfitidea点击:

PKIX path building failed while making SSL connection

javasslintegrationssl-certificate

提问by Vivin Paliath

I'm integrating with a Merchant Account called CommWeb and I'm sending an SSL post to their URL (https://migs.mastercard.com.au/vpcdps). When I try to send the post, I get the following exception:

我正在与一个名为 CommWeb 的商家帐户集成,并且我正在向他们的 URL ( https://migs.mastercard.com.au/vpcdps)发送 SSL 帖子。当我尝试发送帖子时,出现以下异常:

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

The code (which I didn't write, and that already exists in our codebase) that performs the post is:

执行帖子的代码(我没有写,并且已经存在于我们的代码库中)是:

public static HttpResponse sendHttpPostSSL(String url, Map<String, String> params) throws IOException {
    PostMethod postMethod = new PostMethod(url);
    for (Map.Entry<String, String> entry : params.entrySet()) {
        postMethod.addParameter(entry.getKey(), StringUtils.Nz(entry.getValue()));
    }

    HttpClient client = new HttpClient();
    int status = client.executeMethod(postMethod);
    if (status == 200) {
        StringBuilder resultBuffer = new StringBuilder();
        resultBuffer.append(postMethod.getResponseBodyAsString());
        return new HttpResponse(resultBuffer.toString(), "");
    } else {
        throw new IOException("Invalid response code: " + status);
    }
}

The documentation for the Merchant Account integration says nothing about certificates. They did provide some sample JSP code that seems to blindly accept certificates:

商家帐户集成的文档没有提及证书。他们确实提供了一些似乎盲目接受证书的示例 JSP 代码:

<%! // Define Static Constants
    // ***********************
public static X509TrustManager s_x509TrustManager = null;
public static SSLSocketFactory s_sslSocketFactory = null;

static {
        s_x509TrustManager = new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } 
        public boolean isClientTrusted(X509Certificate[] chain) { return true; } 
        public boolean isServerTrusted(X509Certificate[] chain) { return true; } 
    };

    java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    try {
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new X509TrustManager[] { s_x509TrustManager }, null);
        s_sslSocketFactory = context.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }
}

...
...
           // write output to VPC
            SSLSocket ssl = (SSLSocket)s_sslSocketFactory.createSocket(s, vpc_Host, vpc_Port, true);
            ssl.startHandshake();
            os = ssl.getOutputStream();
            // get response data from VPC
            is = ssl.getInputStream();
...
...
%>

Our webapp has a keystore, and I tried adding the certificate (which I exported from firefox) using the keytoolcommand, but that didn't work and I got the same error. I've tried solutions on the web (importing the key and using System.setProperty) but that seems kind of clunky and it didn't work (gave me a NoSuchAlgorithmError). Any help is appreciated!

我们的 web 应用程序有一个密钥库,我尝试使用keytool命令添加证书(我从 firefox 导出的),但这不起作用,我得到了同样的错误。我已经在网络上尝试过解决方案(导入密钥并使用System.setProperty),但这似乎有点笨拙而且没有用(给了我一个NoSuchAlgorithmError)。任何帮助表示赞赏!

采纳答案by President James K. Polk

Evidently the valicert class 3 CA certificate is not in your default truststore (which is probably the cacerts file in your JRE lib/security directory, but see the JSSE documentationfor the full story).

显然,valicert class 3 CA 证书不在您的默认信任库中(这可能是您的 JRE lib/security 目录中的 cacerts 文件,但请参阅JSSE 文档以了解完整故事)。

You could add this certificate to the cacerts file, but I don't recommend this. Instead, I think you should create your own truststore file (which can be a copy of the cacerts file) and add the valicert root ca to this. Then point to this file with the javax.net.ssl.trustStoresystem property.

您可以将此证书添加到 cacerts 文件中,但我不建议这样做。相反,我认为您应该创建自己的信任库文件(可以是 cacerts 文件的副本)并将 valicert root ca 添加到其中。然后用javax.net.ssl.trustStore系统属性指向这个文件。

回答by Vivin Paliath

I figure I should update this answer with what I actually did. Using the documentation that GregS provided, I created a trust manager for valicert. In the trust manager, I load the certificate files:

我想我应该用我实际所做的来更新这个答案。使用 GregS 提供的文档,我为 valicert 创建了一个信任管理器。在信任管理器中,我加载证书文件:

public class ValicertX509TrustManager implements X509TrustManager {

    X509TrustManager pkixTrustManager;

    ValicertX509TrustManager() throws Exception {

        String valicertFile = "/certificates/ValicertRSAPublicRootCAv1.cer";
        String commwebDRFile = "/certificates/DR_10570.migs.mastercard.com.au.crt";
        String commwebPRODFile = "/certificates/PROD_10549.migs.mastercard.com.au.new.crt";

        Certificate valicert = CertificateFactory.getInstance("X509").generateCertificate(this.getClass().getResourceAsStream(valicertFile));
        Certificate commwebDR = CertificateFactory.getInstance("X509").generateCertificate(this.getClass().getResourceAsStream(commwebDRFile));
        Certificate commwebPROD = CertificateFactory.getInstance("X509").generateCertificate(this.getClass().getResourceAsStream(commwebPRODFile));

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, "".toCharArray());
        keyStore.setCertificateEntry("valicert", valicert);
        keyStore.setCertificateEntry("commwebDR", commwebDR);
        keyStore.setCertificateEntry("commwebPROD", commwebPROD);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX");
        trustManagerFactory.init(keyStore);

        TrustManager trustManagers[] = trustManagerFactory.getTrustManagers();

        for(TrustManager trustManager : trustManagers) {
            if(trustManager instanceof X509TrustManager) {
                pkixTrustManager = (X509TrustManager) trustManager;
                return;
            }
        }

        throw new Exception("Couldn't initialize");
    }

    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        pkixTrustManager.checkServerTrusted(chain, authType);
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        pkixTrustManager.checkServerTrusted(chain, authType);
    }

    public X509Certificate[] getAcceptedIssuers() {
        return pkixTrustManager.getAcceptedIssuers();
    }
}

Now, using this trust manager, I had to create a socket factory:

现在,使用这个信任管理器,我必须创建一个套接字工厂:

public class ValicertSSLProtocolSocketFactory implements ProtocolSocketFactory {

    private SSLContext sslContext = null;

    public ValicertSSLProtocolSocketFactory() {
        super();
    }

    private static SSLContext createValicertSSLContext() {
        try {
            ValicertX509TrustManager valicertX509TrustManager = new ValicertX509TrustManager();
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new ValicertX509TrustManager[] { valicertX509TrustManager}, null);
            return context;
        }

        catch(Exception e) {
            Log.error(Log.Context.Net, e);
            return null;
        }
    }

    private SSLContext getSSLContext() {
        if(this.sslContext == null) {
            this.sslContext = createValicertSSLContext();
        }

        return this.sslContext;
    }

    public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException {
        return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
    }

    public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException {
        if(params == null) {
            throw new IllegalArgumentException("Parameters may not be null");
        }

        int timeout = params.getConnectionTimeout();
        SocketFactory socketFactory = getSSLContext().getSocketFactory();

        if(timeout == 0) {
            return socketFactory.createSocket(host, port, localAddress, localPort);
        }

        else {
            Socket socket = socketFactory.createSocket();
            SocketAddress localAddr = new InetSocketAddress(localAddress, localPort);
            SocketAddress remoteAddr = new InetSocketAddress(host, port);
            socket.bind(localAddr);
            socket.connect(remoteAddr, timeout);
            return socket;
        }
    }

    public Socket createSocket(String host, int port) throws IOException {
        return getSSLContext().getSocketFactory().createSocket(host, port);
    }

    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
        return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    public boolean equals(Object obj) {
        return ((obj != null) && obj.getClass().equals(ValicertSSLProtocolSocketFactory.class));
    }

    public int hashCode() {
        return ValicertSSLProtocolSocketFactory.class.hashCode();
    }
}

Now I just register a new protocol:

现在我只注册一个新协议:

Protocol.registerProtocol("vhttps", new Protocol("vhttps", new ValicertSSLProtocolSocketFactory(), 443));
PostMethod postMethod = new PostMethod(url);
for (Map.Entry<String, String> entry : params.entrySet()) {
    postMethod.addParameter(entry.getKey(), StringUtils.Nz(entry.getValue()));
}

HttpClient client = new HttpClient();
int status = client.executeMethod(postMethod);
if (status == 200) {
    StringBuilder resultBuffer = new StringBuilder();
    resultBuffer.append(postMethod.getResponseBodyAsString());
    return new HttpResponse(resultBuffer.toString(), "");
} else {
    throw new IOException("Invalid response code: " + status);
}

The only disadvantage is that I had to create a specific protocol (vhttps) for this particular certificate.

唯一的缺点是我必须vhttps为这个特定的证书创建一个特定的协议 ( )。