繁体   English   中英

对等方未在Java中进行身份验证

[英]Peer not authenticated in java

我去了几乎所有与此例外相关的帖子。 实际上,我的问题是我有一个Java应用程序,通过该应用程序可以访问URL并从中获取响应。

到达网址的代码是:

HttpGet getRequest = new HttpGet("https://urlto.esb.com");
HttpResponse httpResponse = null;       
DefaultHttpClient httpClient = new DefaultHttpClient();
httpResponse = httpClient.execute(getRequest); 

在这里,我得到javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

因此,经过一些Google搜索后,我知道可以在运行应用程序的Java密钥库中导入证书。 所以我在密钥库中导入了证书,并且此代码有效。 但是我不想要这种解决方案,因此在进行更多搜索之后,我知道可以将TrustManager用于同一事物,而无需将证书导入密钥库。 因此,我编写了如下代码:

@Test
    public void withTrustManeger() throws Exception {
        DefaultHttpClient httpclient = buildhttpClient();
        HttpGet httpGet = new HttpGet("https://urlto.esb.com");
        HttpResponse response = httpclient.execute( httpGet );

        HttpEntity httpEntity = response.getEntity();
        InputStream inputStream = httpEntity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                inputStream));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        inputStream.close();
        String jsonText = sb.toString();
        System.out.println(jsonText);
    }

    private DefaultHttpClient buildhttpClient() throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, getTrustingManager(), new java.security.SecureRandom());

        SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
        Scheme sch = new Scheme("https", 443, socketFactory);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        return httpclient;
    }

    private TrustManager[] getTrustingManager() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                // Do nothing               
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                // Do nothing
            }

        } };
        return trustAllCerts;
    }

该代码也可以正常工作,但是我的问题是我没有检查与证书相关的任何内容,而是如何信任连接。 调试后,我知道只有checkServerTrusted在运行。 因此,我在checkServerTrusted编写了一些内容,以验证证书中附带的certs以及应用程序中的.cer或.crt文件中的certs

每个帮助将不胜感激。

@EpicPandaForce之后更新(使用Apache HttpClient 4.3)

        try 
        {
            keyStore = KeyStore.getInstance("JKS");
            InputStream inputStream = new FileInputStream("E:\\Desktop\\esbcert\\keystore.jks");
            keyStore.load(inputStream, "key".toCharArray());
            SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(keyStore, new TrustSelfSignedStrategy());
            sslcontext = sslContextBuilder.build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
            HttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            HttpGet httpGet = new HttpGet("https://url.esb.com");
            HttpResponse response = httpclient.execute( httpGet );

            HttpEntity httpEntity = response.getEntity();
            InputStream httpStram = httpEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpStram));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            httpStram.close();
            inputStream.close();
            String jsonText = sb.toString();
            System.out.println(jsonText);

        } 
        catch(Exception e) 
        {
            System.out.println("Loading keystore failed.");
            e.printStackTrace();
        }

从技术上讲,看到您正在使用Apache HttpClient 4.x时,以下是一个更简单的解决方案:

    SSLContext sslcontext = null;
    try {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom()
            .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslcontext = sslContextBuilder.build();

像这样初始化trustStore地方

    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance("BKS", BouncyCastleProvider.PROVIDER_NAME); //you can use JKS if that is what you have
        InputStream inputStream = new File("pathtoyourkeystore");
        try {
            keyStore.load(inputStream, "password".toCharArray());
        } finally {
            inputStream.close();
        }
    } catch(Exception e) {
        System.out.println("Loading keystore failed.");
        e.printStackTrace();
    }
    return keyStore;
}

然后创建HttpClient

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
httpclient = HttpClients
                .custom()
                .setSSLSocketFactory(sslsf).build();

编辑:对我来说确切的代码是这样的:

        SSLContextBuilder sslContextBuilder = SSLContexts.custom()
            .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslcontext = sslContextBuilder.build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            sslcontext, new String[] {"TLSv1"}, null,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
        );
        httpclient = HttpClients
            .custom()
            .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
            .setSSLSocketFactory(sslsf).build();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM