如何忽略自签名证书并禁止对等体未经过身份验证的错误

时间:2013-01-30 16:09:31

标签: java apache-httpclient-4.x self-signed

我正在尝试向使用自签名证书的服务器发送Https Post请求,并且我收到错误的异常:peer not authenticated

我用Google搜索并发现问题的原因是服务器正在使用自签名的ceritficate。我怎么能抑制这个错误?

我正在使用以下函数发送帖子请求:

public String sendPost(final String request, final String postData) throws ClientProtocolException, IOException  {
    String result = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(request);
    ByteArrayEntity postDataEntity = new ByteArrayEntity(postData.getBytes());
    httpPost.setEntity(postDataEntity);
    CloseableHttpResponse response = httpclient.execute(httpPost);
    try {
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }
    return result;

}

我错过了什么来压制这个错误?我不想尝试捕捉这个例外。 我想正确配置它,以便接受自签名证书。我正在使用 Httpclient 4.1。

谢谢你!

2 个答案:

答案 0 :(得分:2)

您将在网上找到这个问题的许多答案(包括ufk的答案)都可以使用,但一点也不安全,因为它们完全忽略了自签名服务器证书。

这消除了SSL连接的许多好处,并使您可以进行中间人攻击。

您可能想要做的是信任特定的自签名服务器证书,而不是盲目地接受任何服务器证书。

关键是在创建SSL上下文时将服务器证书链的副本放入信任存储区。

执行此操作的代码有点太长,无法在此处发布,但事实上,我正在撰写有关在Android上执行此操作的博客文章。博客文章尚未发布,但示例代码可在GitHub上找到。

答案 1 :(得分:0)

public String sendPost(final String request, final String postData) throws ClientProtocolException, IOException, NoSuchAlgorithmException, KeyManagementException  {
    String result = null;
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                        System.out.println("getAcceptedIssuers =============");
                        return null;
                }

                public void checkClientTrusted(X509Certificate[] certs,
                                String authType) {
                        System.out.println("checkClientTrusted =============");
                }

                public void checkServerTrusted(X509Certificate[] certs,
                                String authType) {
                        System.out.println("checkServerTrusted =============");
                }
    } }, new SecureRandom());

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(new SSLSocketFactory(sslContext)).build();
    HttpPost httpPost = new HttpPost(request);
    ByteArrayEntity postDataEntity = new ByteArrayEntity(postData.getBytes());
    httpPost.setEntity(postDataEntity);
    CloseableHttpResponse response = httpclient.execute(httpPost);
    try {
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }
    return result;

}