Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 这是接受自签名证书的有效方法吗?_Java_Certificate - Fatal编程技术网

Java 这是接受自签名证书的有效方法吗?

Java 这是接受自签名证书的有效方法吗?,java,certificate,Java,Certificate,我编写此代码是为了接受来自服务器的所有自签名证书: private TrustManager[] createTrustManager() { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null;

我编写此代码是为了接受来自服务器的所有自签名证书:

private TrustManager[] createTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                if (!chain[0].getIssuerDN().equals(chain[0].getSubjectDN())) {
                    throw new CertificateException("This is not a self-signed certificate");
                }
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                // leave blank to trust every client
            }
        }};
        return trustAllCerts;
    }

这是一种有效且充分的方法吗?

尽管它起到了作用,但您的方法基本上否定了正确的PKI的目的。如果您盲目信任任何自签名证书,那么使用TLS毫无意义-任何人都可以创建一个自签名证书,该证书将通过您的
TrustManager

因此,如果您希望安全,那么您应该首先确定您的客户端应用程序将与哪些服务器通信,然后获取链接到这些服务的TLS服务器证书(在您的场景中,每个证书都是自签名的,因此您不必关心中间证书)

现在,使用这些证书,您创建了一个JKS“信任存储”文件并将证书放入其中-这是您要信任的证书集,不包含在该文件中的证书将被拒绝。要创建JKS文件,可以使用Java的命令,也可以使用
KeyStore
API以编程方式创建

最后,您将创建
SSLContext
供您的
HttpClient
init
使用的
TrustManager
如下所示:

KeyStore ks = KeyStore.getInstance("JKS");
ks.load(fin, pwd);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(ks);

其中
fin
是您的“信任存储”的
InputStream
,而
pwd
是您用来加密它的密码。默认的
TrustManager
实现只需使用一组受信任的证书,其余的由您处理。

您使用的是Apache
HttpClient
还是Sun的
HttpURLConnection