Peer未在java中进行身份验证 [英] Peer not authenticated in java

查看:131
本文介绍了Peer未在java中进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经去了几乎所有与此例外相关的帖子。实际上我的问题是我有一个java应用程序,我通过它来获取URL并从中获得响应。

I have gone to almost all the post related to this exception. Actually my problem is I have an java application through which I am hitting an URL and getting response from it.

命中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

因此,经过一些谷歌搜索后,我才知道我可以在运行应用程序的java的密钥库中导入证书。所以我在密钥库中导入了证书,这段代码正常运行。但是我不想要这个解决方案所以经过一些搜索之后我才知道我可以使用 TrustManager 来做同样的事情,而无需将证书导入密钥库。所以我编写了如下代码:

So after some Google search I come to know that I can import certificate in keystore of java where the application is running. so I imported certificate in keystore and this code is working. but i don't want this solution so after some more searching I come to know that I can use TrustManager for the same thing without importing certificate into keystore. So I have written code like:

@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文件。

This code is also working but My question is I am not checking anything related to certificates then how connection is trusted. after debugging I come to know that only checkServerTrusted is hitting. So I have write something in checkServerTrusted to validate certificates that come in certs and the one which is in my application like some .cer or .crt file.

我们将不胜感激每一个帮助。

Every Help will be appreciated.

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

Update after @EpicPandaForce (Using 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,一个更简单的解决方案如下:

Technically, seeing as you are using Apache HttpClient 4.x, a simpler solution would be the following:

    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

And then create the HttpClient

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

编辑:我的确切代码是:

Exact code for me was this:

        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();

这篇关于Peer未在java中进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆