专栏首页宝哥技术杂谈一桩由ssl证书过期引起的血案
原创

一桩由ssl证书过期引起的血案

公司全部站点升级了https,升级过程由同事们完成,我没有过问细节。ssl证书使用的是阿里云 的【Symantec免费版 SSL】一年免费。

前段时间,运营小伙伴反馈,有两个网站不能正常使用。一个是使用登录不好用。另外一个是支付中心回调网银不好用。同事们努力排查一周,没有找到解决方案。

了解了情况后,和同事要了错误日志:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: timestamp check failed

完整的代码日志见:https://paste.ubuntu.com/p/Fyc8XgVb8s/

顺便在这里给大家推荐一个好玩的工具:程序员们,寻求帮助时需贴代码或大长串异常信息的,可以利用https://paste.ubuntu.com

回到正题:

通过异常信息,可以很容易的判断与ssl相关,询问了运维的小伙伴,了解到,前段时间ssl证书过期,重新更换了证书。

好嘛,没有办法,只好下载代码,翻看代码,异常点是使用http client 的post请求,对ssl没有做任何处理。

由于,部分模块属于核心依赖的基础类,又不想大规模改动,于是尝试通过http client 绕过ssl证书的办法,经测试通过,以上两个问题,同时解决。

现将处理的核心代码分享给大家,以供参考:

package com.sevens.pay.thirdparty.common.util;


import com.sevens.pay.thirdparty.common.model.HttpResult;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;

public class HttpClientTools {

    /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[] { trustManager }, null);
        return sc;
    }

    /**
     *
     * @param url
     * @param Params
     * @return
     * @throws HttpException
     * @throws IOException
     * @throws KeyManagementException
     * @throws NoSuchAlgorithmException
     */
    public static HttpResult post(String url, List<NameValuePair> Params) throws HttpException, IOException, KeyManagementException, NoSuchAlgorithmException {
        String body = "";

        //采用绕过验证的方式处理https请求
        SSLContext sslcontext = createIgnoreVerifySSL();
        //设置协议http和https对应的处理socket链接工厂的对象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslcontext))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);

        //创建自定义的httpclient对象
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
        HttpResult httpResult = null;

        try{
            //创建post方式请求对象


            HttpPost httpPost = new HttpPost(url);

            HttpEntity httpEntity = new UrlEncodedFormEntity(Params);

            httpPost.setEntity(httpEntity);


            //指定报文头Content-type、User-Agent
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");

            httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");



            //执行请求操作,并拿到结果(同步阻塞)
            CloseableHttpResponse response = client.execute(httpPost);


            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
            System.out.println(body);
            httpResult = new HttpResult();
            httpResult.setStatusCode(response.getStatusLine().getStatusCode());
            httpResult.setResult(body);

            System.out.println("http status:"+httpResult.getStatusCode());

            //释放链接
            response.close();

        }finally{
            client.close();
        }
        return  httpResult;
    }
    /**
     *
     * @param url
     * @return
     * @throws HttpException
     * @throws IOException
     * @throws KeyManagementException
     * @throws NoSuchAlgorithmException
     */
    public static HttpResult get(String url) throws HttpException, IOException, KeyManagementException, NoSuchAlgorithmException {
        String body = "";

        //采用绕过验证的方式处理https请求
        SSLContext sslcontext = createIgnoreVerifySSL();
        //设置协议http和https对应的处理socket链接工厂的对象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslcontext))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);

        //创建自定义的httpclient对象
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
        HttpResult httpResult = null;

        try{

            //创建post方式请求对象
            HttpGet httpPost = new HttpGet(url);


            //指定报文头Content-type、User-Agent
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");

            httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");



            //执行请求操作,并拿到结果(同步阻塞)
            CloseableHttpResponse response = client.execute(httpPost);


            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
            System.out.println(body);
            httpResult = new HttpResult();
            httpResult.setStatusCode(response.getStatusLine().getStatusCode());
            httpResult.setResult(body);

            System.out.println("http status:"+httpResult.getStatusCode());

            //释放链接
            response.close();

        }finally{
            client.close();
        }
        return  httpResult;
    }

    public final static void main(String[] args){
        try {


            String url = "https://passport.baidu.com/v1/tickets";//已改,这是伪地址

            List<NameValuePair> parms = new ArrayList<NameValuePair>();

            parms.add(new BasicNameValuePair("username","xxxxxxxx"));
            parms.add(new BasicNameValuePair("password","xxxxx"));

            post(url,parms);


        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }


}

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • editormd实现Markdown编辑器写文章功能

    想在项目里引入Markdown编辑器实现写文章功能,网上找到一款开源的插件editormd.js

    SmileNicky
  • 一种基于深度学习的低成本细胞生物学研究方法

    答案是肯定的!在本文中,我们提出了一种灵活且低廉的方法来解决生物学问题,该方法非常适合业余科学家。我们充分利用了低成本的图像设备(FoldScope显微镜)、公...

    用户7623498
  • My Notepad

    I have spent near more two weeks to write this Notepad application. At this mome...

    Hongten
  • 通过 HttpClient 从指定服务器获取数据

    week
  • 使用dropwizard(3)-加入DI-dagger2

    前言 习惯了Spring全家桶,对spring的容器爱不释手。使用dropwizard,看起来确实很轻,然而,真正使用的时候不得不面临一个问题。我们不可能一个...

    Ryan-Miao
  • Windows Server 2012 R2怎么添加Windows Server Backup 功能

    今天想要对Windows Server 2012 R2进行备份操作,发现在菜单里发现没有这个功能,看来只能添加了

    BigYoung小站
  • HttpClient 发送get请求并返回Json数据

    http://baike.baidu.com/api/openapi/BaikeLemmaCardApi?scope=103&format=json&appid...

    week
  • 第四篇:SpringBoot与任务

    版权声明:本文为博主原创文章,未经博主允许不得转载。 ...

    用户1212940
  • 谷歌跨界音乐圈:AI用上千乐器数据创造出人类没听过的声音,来听听看!

    大数据文摘
  • SpringBoot入门建站全系列(二十八)整合Kafka做日志监控

    Apache Kafka是一个分布式发布 - 订阅消息系统和一个强大的队列,可以处理大量的数据,并使您能够将消息从一个端点传递到另一个端点。 Kafka适合离线...

    品茗IT

扫码关注云+社区

领取腾讯云代金券