使用HTTPS的HttpGet:SSLPeerUnverifiedException

时间:2010-02-22 04:23:56

标签: java ssl https httpclient

使用HttpClient时,尝试通过HTTPS进行通信时收到以下错误:

  

线程“main”中的异常javax.net.ssl.SSLPeerUnverifiedException:peer未经过身份验证。

这是我的代码:

URI loginUri = new URI("https://myUrl.asp");

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet( loginUri );
HttpResponse response = httpclient.execute( httpget );

如何抑制或删除此错误?

5 个答案:

答案 0 :(得分:17)

注意:请勿在生产代码中执行此操作,而是使用http代替,或者按照上面的建议使用实际的自签名公钥。

在HttpClient 4.xx上:

import static org.junit.Assert.assertEquals;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;

public class HttpClientTrustingAllCertsTest {

    @Test
    public void shouldAcceptUnsafeCerts() throws Exception {
        DefaultHttpClient httpclient = httpClientTrustingAllSSLCerts();
        HttpGet httpGet = new HttpGet("https://host_with_self_signed_cert");
        HttpResponse response = httpclient.execute( httpGet );
        assertEquals("HTTP/1.1 200 OK", response.getStatusLine().toString());
    }

    private DefaultHttpClient httpClientTrustingAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
        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;
    }
}

答案 1 :(得分:16)

此答案接着是owlsteadMat的回复。它适用于SE / EE安装,而不适用于ME /移动/ Android SSL。

由于还没有人提及它,我会提到“生产方式”来解决这个问题: 按照AuthSSLProtocolSocketFactory class in HttpClient中的步骤更新您的信任商店&重点商店。

  1. 导入可信证书并生成信任库文件
  2. keytool -import -alias "my server cert" -file server.crt -keystore my.truststore

    1. 生成一个新密钥(使用与信任库相同的密码)
    2. keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore

      1. 发出证书签名请求(CSR)
      2. keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore

        1. (自签名或获得证书签名)

        2. 导入可信CA根证书

        3. keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore

          1. 导入包含完整证书链的PKCS#7文件
          2. keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore

            1. 验证生成的密钥库文件的内容
            2. keytool -list -v -keystore my.keystore

              如果您没有服务器证书,请以JKS格式生成一个,然后将其导出为CRT文件。 Source: keytool documentation

              keytool -genkey -alias server-alias -keyalg RSA -keypass changeit
                  -storepass changeit -keystore my.keystore
              
              keytool -export -alias server-alias -storepass changeit
                  -file server.crt -keystore my.keystore
              

答案 2 :(得分:12)

使用HttpClient 3.x,您需要这样做:

Protocol easyHttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", easyHttps);

可以找到EasySSLProtocolSocketFactory的实现here

答案 3 :(得分:0)

返回“secureClient”的方法(在Java 7环境中 - NetBeans IDE和GlassFish Server:默认端口为https 3920),希望这可能有所帮助:

public DefaultHttpClient secureClient() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    SSLSocketFactory sf;

    KeyStore trustStore;
    FileInputStream trustStream = null;
    File truststoreFile;
    // java.security.cert.PKIXParameters for the trustStore
    PKIXParameters pkixParamsTrust;

    KeyStore keyStore;
    FileInputStream keyStream = null;
    File keystoreFile;
    // java.security.cert.PKIXParameters for the keyStore
    PKIXParameters pkixParamsKey;

    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        truststoreFile = new File(TRUSTSTORE_FILE);
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystoreFile = new File(KEYSTORE_FILE);
        try {
            trustStream = new FileInputStream(truststoreFile);
            keyStream = new FileInputStream(keystoreFile);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            trustStore.load(trustStream, PASSWORD.toCharArray());
            keyStore.load(keyStream, PASSWORD.toCharArray());
        } catch (IOException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CertificateException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            pkixParamsTrust = new PKIXParameters(trustStore);
            // accepts Server certificate generated with keytool and (auto) signed by SUN
            pkixParamsTrust.setPolicyQualifiersRejected(false);
        } catch (InvalidAlgorithmParameterException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            pkixParamsKey = new PKIXParameters(keyStore);
            // accepts Client certificate generated with keytool and (auto) signed by SUN
            pkixParamsKey.setPolicyQualifiersRejected(false);
        } catch (InvalidAlgorithmParameterException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            sf = new SSLSocketFactory(trustStore);
            ClientConnectionManager manager = httpclient.getConnectionManager();
            manager.getSchemeRegistry().register(new Scheme("https", 3920, sf));
        } catch (KeyManagementException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnrecoverableKeyException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    // use the httpclient for any httpRequest
    return httpclient;
}

答案 4 :(得分:0)

您的本地JVM或远程服务器可能没有所需的密码。去这里

https://www.oracle.com/java/technologies/javase-jce8-downloads.html

并下载包含以下内容的zip文件: US_export_policy.jar 和 local_policy.jar

替换现有文件(您需要在JVM中找到现有路径)。

在Mac上,我的路径在这里。 /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/security

这对我有用。