1

自己署名証明書を使用しているサーバーに Https Post リクエストを送信しようとしていますが、次のエラーで例外が発生します: peer not authenticated.

問題の原因は、サーバーが自己署名証明書を使用していることです。どうすればこのエラーを抑制できますか?

次の関数を使用して投稿リクエストを送信しています。

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を使用しています。

ありがとう!

4

2 に答える 2

2

この質問に対する Web 上の回答 (ufk の回答を含む) の多くは機能しますが、自己署名サーバー証明書を完全に無視するため、まったく安全ではありません。

これにより、SSL 接続の利点の多くが失われ、中間者攻撃にさらされる可能性があります。

おそらく代わりにやりたいことは、サーバー証明書を盲目的に受け入れるのではなく、特定の自己署名サーバー証明書を信頼することです。

これの鍵は、SSL コンテキストを作成するときに、サーバーの証明書チェーンのコピーをトラスト ストアに入れることです。

これを行うためのコードは、ここに投稿するには少し長すぎますが、現在、Android でこれを行うことに関するブログ投稿に取り組んでいます。ブログ投稿はまだ公開されていませんが、サンプル コードはGitHubで入手できます。

于 2013-01-30T18:38:27.990 に答える
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;

}
于 2013-01-30T17:52:49.140 に答える