知识点

相关文章

更多

最近更新

更多

HttpClient 获取HTTPS证书和忽略证书错误

2019-04-09 22:42|来源: 网路

以下教程演示了如何使用Apache HttpClient 4.5从资源服务器获取证书。 证书用于通过使用SSL / TLS的HTTPS保护客户端和服务器之间的连接。 当您需要有关证书的详细信息时,例如:证书何时到期?谁颁发证书?等等。或者在某些情况下需要读取服务器证书。 在下面的例子中,我们将详细解释如何实现。

Maven依赖关系

我们使用maven来管理依赖关系,并使用Apache HttpClient 4.5版本。 将以下依赖项添加到您的项目中,以便创建HTTP DELETE请求方法。

pom.xml 文件的内容如下 -

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yiibai.httpclient.httmethods</groupId>
    <artifactId>http-get</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <url>https://memorynotfound.com</url>
    <name>httpclient - ${project.artifactId}</name>

    <dependencies>
        <!-- Apache Commons IO -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


HTTP获取服务器证书示例

在以下示例中,我们向https://www.baidu.com发出请求以获取服务器证书。 首先,我们创建一个HttpResponseInterceptor,它将从SSLSession中读取证书(如果存在),并将证书添加到HttpContext中,以便稍后用于处理。

接下来,创建一个自定义的HttpClient并使用addInterceptorLast()工厂方法添加拦截器。

最后,向资源服务器发出一个HttpGet请求,并从HttpContext获取服务器证书,我们之前将它们放在这里。 现在拥有了证书,然后遍历集合并将一些数据打印到控制台。

文件:HttpClientGetServerCertificate.java -

import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.DateUtils;
import org.apache.http.conn.ManagedHttpClientConnection;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

/**
 * This example demonstrates how to obtain server certificates {@link X509Certificate}.
 */
public class HttpClientGetServerCertificate {

    public static final String PEER_CERTIFICATES = "PEER_CERTIFICATES";

    public static void main(String... args) throws IOException {

        // create http response certificate interceptor
        HttpResponseInterceptor certificateInterceptor = (httpResponse, context) -> {
            ManagedHttpClientConnection routedConnection = (ManagedHttpClientConnection)context.getAttribute(HttpCoreContext.HTTP_CONNECTION);
            SSLSession sslSession = routedConnection.getSSLSession();
            if (sslSession != null) {

                // get the server certificates from the {@Link SSLSession}
                Certificate[] certificates = sslSession.getPeerCertificates();

                // add the certificates to the context, where we can later grab it from
                context.setAttribute(PEER_CERTIFICATES, certificates);
            }
        };

        // create closable http client and assign the certificate interceptor
        CloseableHttpClient httpClient = HttpClients.custom().addInterceptorLast(certificateInterceptor).build();

        try {

            // make HTTP GET request to resource server
            HttpGet httpget = new HttpGet("https://www.baidu.com");
            System.out.println("Executing request " + httpget.getRequestLine());

            // create http context where the certificate will be added
            HttpContext context = new BasicHttpContext();
            httpClient.execute(httpget, context);

            // obtain the server certificates from the context
            Certificate[] peerCertificates = (Certificate[])context.getAttribute(PEER_CERTIFICATES);

            // loop over certificates and print meta-data
            for (Certificate certificate : peerCertificates){
                X509Certificate real = (X509Certificate) certificate;
                System.out.println("----------------------------------------");
                System.out.println("Type: " + real.getType());
                System.out.println("Signing Algorithm: " + real.getSigAlgName());
                System.out.println("IssuerDN Principal: " + real.getIssuerX500Principal());
                System.out.println("SubjectDN Principal: " + real.getSubjectX500Principal());
                System.out.println("Not After: " + DateUtils.formatDate(real.getNotAfter(), "dd-MM-yyyy"));
                System.out.println("Not Before: " + DateUtils.formatDate(real.getNotBefore(), "dd-MM-yyyy"));
            }

        } finally {
            // close httpclient
            httpClient.close();
        }
    }
}


执行上面示例代码,得到以下结果 -

Executing request GET https://www.baidu.com HTTP/1.1
----------------------------------------
Type: X.509
Signing Algorithm: SHA256withRSA
IssuerDN Principal: CN=Symantec Class 3 Secure Server CA - G4, OU=Symantec Trust Network, O=Symantec Corporation, C=US
SubjectDN Principal: CN=baidu.com, OU=service operation department., O="BeiJing Baidu Netcom Science Technology Co., Ltd", L=beijing, ST=beijing, C=CN
Not After: 17-08-2018
Not Before: 29-06-2017
----------------------------------------
Type: X.509
Signing Algorithm: SHA256withRSA
IssuerDN Principal: CN=VeriSign Class 3 Public Primary Certification Authority - G5, OU="(c) 2006 VeriSign, Inc. - For authorized use only", OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
SubjectDN Principal: CN=Symantec Class 3 Secure Server CA - G4, OU=Symantec Trust Network, O=Symantec Corporation, C=US
Not After: 30-10-2023
Not Before: 31-10-2013
----------------------------------------
Type: X.509
Signing Algorithm: SHA1withRSA
IssuerDN Principal: OU=Class 3 Public Primary Certification Authority, O="VeriSign, Inc.", C=US
SubjectDN Principal: CN=VeriSign Class 3 Public Primary Certification Authority - G5, OU="(c) 2006 VeriSign, Inc. - For authorized use only", OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
Not After: 07-11-2021
Not Before: 08-11-2006


忽略证书错误

通常,开发人员将在本地机器上或项目的开发阶段使用自签名证书。 默认情况下,HttpClient(和Web浏览器)不会接受不可信的连接。 但是,可以配置HttpClient以允许不可信的自签名证书。

注意:这是一个可能存在安全风险,因为您将其用于生产时,基本上会禁用所有的认证检查,这可通导致受到攻击。

在这个例子中,我们演示了如何忽略Apache HttpClient 4.5中的SSL / TLS证书错误。

自签名证书错误

当您尝试向使用自签名证书的服务器发出请求并且证书未被客户端知晓时,将收到以下异常 -

Caused by: 
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: 
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: 
unable to find valid certification path to requested target

接受自签名证书

我们配置一个自定义的HttpClient。 首先使用SSLContextBuilder设置SSLContext并使用TrustSelfSignedStrategy类来允许自签名证书。 使用NoopHostnameVerifier本质上关闭主机名验证。 创建SSLConnectionSocketFactory并传入SSLContext和HostNameVerifier,并使用工厂方法构建HttpClient。

文件:HttpClientAcceptSelfSignedCertificate.java -

import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.*;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * This example demonstrates how to ignore certificate errors.
 * These errors include self signed certificate errors and hostname verification errors.
 */
public class HttpClientAcceptSelfSignedCertificate {

    public static void main(String... args)  {

        try (CloseableHttpClient httpclient = createAcceptSelfSignedCertificateClient()) {
            HttpGet httpget = new HttpGet("https://www.656463.com");
            System.out.println("Executing request " + httpget.getRequestLine());

            httpclient.execute(httpget);
            System.out.println("----------------------------------------");
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static CloseableHttpClient createAcceptSelfSignedCertificateClient()
            throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

        // use the TrustSelfSignedStrategy to allow Self Signed Certificates
        SSLContext sslContext = SSLContextBuilder
                .create()
                .loadTrustMaterial(new TrustSelfSignedStrategy())
                .build();

        // we can optionally disable hostname verification. 
        // if you don't want to further weaken the security, you don't have to include this.
        HostnameVerifier allowAllHosts = new NoopHostnameVerifier();

        // create an SSL Socket Factory to use the SSLContext with the trust self signed certificate strategy
        // and allow all hosts verifier.
        SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);

        // finally create the HttpClient using HttpClient factory methods and assign the ssl socket factory
        return HttpClients
                .custom()
                .setSSLSocketFactory(connectionFactory)
                .build();
    }
}


执行上面示例代码,得到以下结果 -

Executing request GET https://www.656463.com HTTP/1.1
----------------------------------------


相关问答

更多
  • 你那个 SSLSocketFactory(ks) 是自己的类? 你有用过 KeyManager.init (...)? 和 TrustManager.init(...) ? 想要在连接建立过程上交互式的弹出确认对话框来的话需要我们自己提供一个 KeyManager 和 TrustManager 的实现类,这有点复杂,你可以看一个 Sun 的 X509KeyManager 是怎么做的,默认地情况下它是从自动搜索匹配的 subject ,我们需要用自己提供的方式弹出确认的过程还不是全自动,另外一个账户可能有多个 ...
  • 您需要使用自己的TrustManager创建一个SSLContext,并使用此上下文创建HTTPS方案。 这里是代码, SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509C ...
  • 只需在URI中指定HTTPS。 new Uri("https://foobar.com/"); Foobar.com将需要一个受信任的SSL证书,否则您的呼叫将以不可信的错误失败。 编辑答案: 具有HttpClient的ClientCertificates WebRequestHandler handler = new WebRequestHandler(); X509Certificate2 certificate = GetMyX509Certificate(); handler.ClientCert ...
  • 以下代码适用于信任自签名证书。 创建客户端时必须使用TrustSelfSignedStrategy : SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( ...
  • 根据MSDN ,因为.NET 4.5以下实例方法是线程安全的 (感谢@ischell): CancelPendingRequests DeleteAsync GetAsync GetByteArrayAsync GetStreamAsync GetStringAsync PostAsync PutAsync SendAsync According to MSDN, since .NET 4.5 The following instance methods are thread safe (thanks @ ...
  • 注意:不要在您不完全信任的网络上使用的生产代码中实现。 特别是公共互联网上的任何事情。 你的问题只是我想知道的。 在我进行了一些搜索之后,结论如下。 以HttpClient方式,您应该从org.apache.http.conn.ssl.SSLSocketFactory创建一个自定义类,而不是一个org.apache.http.conn.ssl.SSLSocketFactory本身。 一些线索可以在这个帖子中找到自定义SSL处理停止在Android 2.2 FroYo上工作 。 一个例子就像... impor ...
  • 您正在UI线程上访问阻止任务的r.Result 。 这会产生死锁,因为内部await尝试在UI线程上恢复。 你需要await它。 You're accessing r.Result, which blocks on the Task, on the UI thread. This creates a deadlock, since the inner await tries to resume on the UI thread. You need to await it instead.
  • SelfSigned CA必须位于服务器上以及连接到服务器的任何客户端上的LocalMachine \ Root存储中。 SSL证书应具有客户端将用于连接到它的确切DNS名称。 它可以在主题备用名称(SAN)扩展中的证书中指定多个DNS名称。 在您的情况下,您正在使用IP地址 您将IP地址放在SAN或 您将IP地址放在hosts文件中,并使用您在发出SSL证书时指定的DNS名称,并在HttpClient中使用此DNS名称 您可以考虑使用XCA颁发证书。 它有很好的GUI,建立在OpenSSL之上。 它具有C ...
  • 密钥库包含您的私钥和相关证书。 信任库包含您信任的证书,因此可用于证书路径构建和验证。 以下是一些可能有用的链接: java.lang.Exception:输入不是X.509证书 将私钥和证书导入Java密钥库 配置密钥库和信任库 The keystore holds your private keys and associated certificates. The truststore hold the certificates that you trust and that can therefore ...
  • 这个MSDN帖子证明了答案。 似乎是对MS部分的疏忽,需要事先对API进行单独的,毫无意义的调用。 好吧。 http://blogs.msdn.com/b/wsdevsol/archive/2015/03/26/how-to-use-a-shared-user-certificate-for-https-authentication-in-an-enterprise-application。 ASPX 摘自文章: 但是,在允许访问存储在共享用户证书存储中的证书的证书私钥之前,安全子系统需要用户确认。 更复杂 ...