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

时间:2014-05-26 08:46:15

标签: 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();

或者有更好的方法吗?

1 个答案:

答案 0 :(得分:3)

这是如何做到的

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();

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