请求https错误: unable to find valid certification path to requested target

错误及原因

当Java客户端请求实现https协议的服务时,出现异常:’unable to find valid certification path to requested target’

是因为服务期端的证书没有被认证,需要做的是把服务端证书导入到Java keystore。

解决方法

使用下面的类安装证书

package com.shanhy.caogen;
/*
 * 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.
 */

import java.io.*;
import java.net.URL;

import java.security.*;
import java.security.cert.*;

import javax.net.ssl.*;

/**
 * 安装证书
 *
 * @author   单红宇(365384722)
 * @myblog  http://blog.youkuaiyun.com/catoop/
 * @create    2016年4月14日
 */
public class InstallCert {

    // 我们要访问的HTTPS服务,如访问 https://www.shanhy.com
    public static final String hostName = "www.shanhy.com";

    public static void main(String[] args) throws Exception {
        args = new String[]{hostName};
        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 <host>[: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);
        }
    }

}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191

该类为包含main方法的入口类,直接运行即可。 
在出现提示后,输入1后回车完成(如果你要放弃并退出输入q即可)。

执行完毕后,在执行该类的当然目录中找到生成的 jssecacerts 文件,然后拷贝该文件到JDK中,如我的是放到:……\jdk1.8.0_60\jre\lib\security 中。

最后再使用之前的Java代码请求HTTPS接口,就不会出现错误了。

<think>嗯,用户遇到了Apollo客户端因为证书问题导致的SSL连接错误,具体报错是“unable to find valid certification path to requested target SSL handshake error”。这个问题通常和SSL证书的信任链有关,也就是说客户端不认可服务器提供的证书,可能因为证书是自签名的,或者没有正确安装到客户端的信任库中。 首先,我需要回忆一下Java如何处理SSL证书。Java有一个叫做cacerts的默认信任库,里面存放了受信任的CA证书。如果Apollo服务端使用的证书不是由这些受信任的CA签发的,比如自签名的或者内部CA签发的,那么Java客户端就会抛出这个错误。这时候,解决方法通常是将服务端的证书导入到客户端的信任库中。 接下来,用户可能需要确认证书的来源。如果是自签名的,需要导出证书,然后使用keytool工具添加到Java的信任库。具体步骤可能包括从浏览器导出证书,或者使用openssl命令从服务器获取。然后执行keytool -import命令来添加证书。需要注意的是,Java的版本不同,默认的信任库路径可能不同,用户需要确认正确的路径。 另外,如果用户的环境是Docker容器,可能需要重新构建镜像,确保信任库的修改被包含进去。或者在启动容器的时候挂载修改后的信任库文件。还有,检查Apollo客户端的配置是否正确,比如是否正确配置了SSL相关的参数,或者有没有可能暂时关闭SSL验证进行测试(虽然不推荐生产环境这么做)。 还有可能涉及到容器内的用户权限问题,比如之前的引用中提到过“unable to find user test”的错误,这可能和容器内的用户权限有关,但当前的问题更可能是证书的问题。不过需要确保执行命令的用户有权限修改信任库文件,否则会出现权限被拒绝的情况,比如在docker_start_user.sh脚本中提到的权限问题。 此外,用户可能需要检查服务端证书的详细信息,确认证书是否过期,域名是否匹配,以及证书链是否完整。有时候中间证书缺失也会导致这样的问题。可以使用openssl s_client -connect命令来检查服务端的证书链情况。 总结一下,解决步骤可能包括:导出服务端证书,导入到Java信任库,处理容器环境下的信任库更新,检查证书的有效性和配置。同时,用户可能需要参考类似问题的解决方案,比如引用[3]中提到的用户不存在的问题,虽然不直接相关,但可能涉及到环境配置的问题,需要注意权限和路径的正确性。</think>### Apollo客户端SSL证书问题解决方案 #### 一、问题定位 出现`unable to find valid certification path to requested target`错误,表示Java客户端未信任服务端SSL证书。常见原因: 1. 服务端使用自签名证书或内部CA证书 2. 证书链不完整 3. 客户端未正确配置信任库 #### 二、解决方案步骤 ##### 1. 导出服务端证书 ```bash openssl s_client -connect <apollo-server-domain>:<port> </dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > apollo.crt ``` *替换`<apollo-server-domain>`和`<port>`为实际地址* ##### 2. 导入证书到Java信任库 ```bash keytool -import -alias apollo_cert -keystore $JAVA_HOME/lib/security/cacerts -file apollo.crt ``` *默认密码:`changeit`* ##### 3. Docker容器特殊处理 若Apollo运行在容器中: ```dockerfile # Dockerfile中添加 COPY apollo.crt /usr/local/share/ca-certificates/ RUN update-ca-certificates ``` 或启动时挂载证书: ```bash docker run -v /path/to/certs:/etc/ssl/certs ... ``` #### 三、验证配置 ```java public class SSLVerify { public static void main(String[] args) throws Exception { URL url = new URL("https://your-apollo-config-url"); url.openConnection().connect(); } } ``` #### 四、替代方案(临时) 修改JVM参数(仅限测试环境): ```bash -Dcom.sun.jndi.ldap.object.disableEndpointIdentification=true ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值