java - Apache httpclient 4.3.3 我如何只接受一个特定的自签名证书

标签 java ssl ssl-certificate httpclient apache-httpclient-4.x

我正在构建一个休息客户端,它应该只接受一个特定证书的响应。我尝试使用响应拦截器来比较哈希值以识别并检查是否使用了正确的证书。但我不知道如何从响应中获取服务器证书。我发现的方法都在 httpclient 4.3.3 中被弃用了。

 CloseableHttpClient httpclient = HttpClients.custom().addInterceptorLast(new HttpResponseInterceptor() {

  @Override
  public void process(HttpResponse response, HttpContext context) throws HttpException, IOException
  {
    //how do I get the certificate here?
    String sha1Hex = DigestUtils.sha1Hex(cert.getEncoded());

    boolean check = sha1Hex.equals("xxxxxxxx");
  }

}).setSSLSocketFactory(sslsf).build();

或者有更好的方法吗?

最佳答案

这是可以做到的

CloseableHttpClient httpclient = HttpClients.custom().addInterceptorLast(new HttpResponseInterceptor() {

    @Override
    public void process(
            HttpResponse response, HttpContext context) throws HttpException, IOException {
        HttpCoreContext coreContext = HttpCoreContext.adapt(context);
        ManagedHttpClientConnection conn = coreContext.getConnection(ManagedHttpClientConnection.class);
        SSLSession sslSession = conn.getSSLSession();
        if (sslSession != null) {
            X509Certificate[] certs = sslSession.getPeerCertificateChain();
            if (certs.length == 1) {
                String sha1Hex = null;
                try {
                    sha1Hex = DigestUtils.sha1Hex(certs[0].getEncoded());
                } catch (CertificateEncodingException ex) {
                    throw new HttpException("Messged up cert", ex);
                }
                boolean check = sha1Hex.equals("xxxxxxxx");
            }
        }
    }

}).setSSLSocketFactory(sslsf).build();

但是,我推荐的更好的方法是使用由您希望客户端信任的证书组成的信任 Material 来初始化客户端的 SSL 上下文。

关于java - Apache httpclient 4.3.3 我如何只接受一个特定的自签名证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23866171/

相关文章:

java - SL4FJ 是否提供与 Log4J PatternLayout 等效的功能?

java - Eclipse Java Luna SR2 - 无法导出项目

html - SSL 导致某些页面元素出现问题

Java double to long 转换报错之谜

java - 当鼠标悬停在工具提示上时如何保持可见?

java - 将证书链写入 PEM 文件

ssl - 如何在 puppet 中完全禁用 SSL 身份验证?

ssl - IP 地址不受 HTTP 严格传输安全保护

SAP 中不受信任的 SSL 对等证书

eclipse - Tomcat Eclipse ERR_SSL_VERSION_OR_CIPHER_MISMATCH