httpsClient抓取证书

在执行webservice的过程中,出现如下异常:

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

这是缺少安全证书时出现的异常,解决方案就是将你要访问的webservice的安全认证证书导入到客户端即可。以下是获取安全证书的一种方法

1,写一个程序专门获取安全证书,参考InstallCert.java:

/*
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.*;
import java.net.URL;

import java.security.*;
import java.security.cert.*;

import javax.net.ssl.*;

public class InstallCert {

    public static void main(String[] args) throws Exception {
    String host;
    int port;
    char[] passphrase;
    if ((args.length == 1) || (args.length == 2)) {
        String[] c = args[0].split(":");
        host = c[0];
        port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
        String p = (args.length == 1) ? "changeit" : args[1];
        passphrase = p.toCharArray();
    } else {
        System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
        return;
    }

    File file = new File("jssecacerts");
    if (file.isFile() == false) {
        char SEP = File.separatorChar;
        File dir = new File(System.getProperty("java.home") + SEP
            + "lib" + SEP + "security");
        file = new File(dir, "jssecacerts");
        if (file.isFile() == false) {
        file = new File(dir, "cacerts");
        }
    }
    System.out.println("Loading KeyStore " + file + "...");
    InputStream in = new FileInputStream(file);
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(in, passphrase);
    in.close();

    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
    SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] {tm}, null);
    SSLSocketFactory factory = context.getSocketFactory();

    System.out.println("Opening connection to " + host + ":" + port + "...");
    SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
    socket.setSoTimeout(10000);
    try {
        System.out.println("Starting SSL handshake...");
        socket.startHandshake();
        socket.close();
        System.out.println();
        System.out.println("No errors, certificate is already trusted");
    } catch (SSLException e) {
        System.out.println();
        e.printStackTrace(System.out);
    }

    X509Certificate[] chain = tm.chain;
    if (chain == null) {
        System.out.println("Could not obtain server certificate chain");
        return;
    }

    BufferedReader reader =
        new BufferedReader(new InputStreamReader(System.in));

    System.out.println();
    System.out.println("Server sent " + chain.length + " certificate(s):");
    System.out.println();
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        X509Certificate cert = chain[i];
        System.out.println
            (" " + (i + 1) + " Subject " + cert.getSubjectDN());
        System.out.println("   Issuer  " + cert.getIssuerDN());
        sha1.update(cert.getEncoded());
        System.out.println("   sha1    " + toHexString(sha1.digest()));
        md5.update(cert.getEncoded());
        System.out.println("   md5     " + toHexString(md5.digest()));
        System.out.println();
    }

    System.out.println("Enter certificate to add to trusted keystore or ‘q‘ to quit: [1]");
    String line = reader.readLine().trim();
    int k;
    try {
        k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
    } catch (NumberFormatException e) {
        System.out.println("KeyStore not changed");
        return;
    }

    X509Certificate cert = chain[k];
    String alias = host + "-" + (k + 1);
    ks.setCertificateEntry(alias, cert);

    OutputStream out = new FileOutputStream("jssecacerts");
    ks.store(out, passphrase);
    out.close();

    System.out.println();
    System.out.println(cert);
    System.out.println();
    System.out.println
        ("Added certificate to keystore ‘jssecacerts‘ using alias ‘"
        + alias + "‘");
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 3);
    for (int b : bytes) {
        b &= 0xff;
        sb.append(HEXDIGITS[b >> 4]);
        sb.append(HEXDIGITS[b & 15]);
        sb.append(‘ ‘);
    }
    return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {

    private final X509TrustManager tm;
    private X509Certificate[] chain;

    SavingTrustManager(X509TrustManager tm) {
        this.tm = tm;
    }

    public X509Certificate[] getAcceptedIssuers() {
        throw new UnsupportedOperationException();
    }

    public void checkClientTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        throw new UnsupportedOperationException();
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        this.chain = chain;
        tm.checkServerTrusted(chain, authType);
    }
    }

}

2.执行 java InstallCert hostname 比如

java InstallCert ecc.fedora.redhat.com

会看到如下信息:

java InstallCert ecc.fedora.redhat.com
Loading KeyStore /usr/jdk/instances/jdk1.5.0/jre/lib/security/cacerts...
Opening connection to ecc.fedora.redhat.com:443...
Starting SSL handshake...

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
	at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
	at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
	at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
	at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:846)
	at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
	at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
	at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:815)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1025)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1038)
	at InstallCert.main(InstallCert.java:63)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:221)
	at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:145)
	at sun.security.validator.Validator.validate(Validator.java:203)
	at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172)
	at InstallCert$SavingTrustManager.checkServerTrusted(InstallCert.java:158)
	at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320)
	at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:839)
	... 7 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:236)
	at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:194)
	at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:216)
	... 13 more

Server sent 2 certificate(s):

 1 Subject CN=ecc.fedora.redhat.com, O=example.com, C=US
   Issuer  CN=Certificate Shack, O=example.com, C=US
   sha1    2e 7f 76 9b 52 91 09 2e 5d 8f 6b 61 39 2d 5e 06 e4 d8 e9 c7
   md5     dd d1 a8 03 d7 6c 4b 11 a7 3d 74 28 89 d0 67 54 

 2 Subject CN=Certificate Shack, O=example.com, C=US
   Issuer  CN=Certificate Shack, O=example.com, C=US
   sha1    fb 58 a7 03 c4 4e 3b 0e e3 2c 40 2f 87 64 13 4d df e1 a1 a6
   md5     72 a0 95 43 7e 41 88 18 ae 2f 6d 98 01 2c 89 68 

Enter certificate to add to trusted keystore or ‘q‘ to quit: [1]

3.输入1,然后直接回车,会在相应的目录下产生一个名为‘jssecacerts’的证书。将证书copy到$JAVA_HOME/jre/lib/security目录下,或者通过以下方式

System.setProperty("javax.net.ssl.trustStore", "D:\\UTA\\DOC_E_Health_XML\\Keystore\\jssecacerts");

注意:要重新启动你的应用服务器,因是静态加载,证书才能被运用上。

时间: 2024-10-31 12:30:10

httpsClient抓取证书的相关文章

Fiddler抓取https证书问题

正常的使用方法  Fiddler 抓包工具总结 大部分问题的解决方案  fiddler4在win7抓取https的配置整理 像我脸一样黑的解决方案  Fiddler https 证书问题 可能的解释: Fiddler自带两个cert engine,一个是makecert,一个是CertEnroll,可能是由于版本问题,makecert能够正常生成证书,但是没办法获取ca认证,造成登录https网站时显示"您的链接不是隐私链接":CertEnroll engine无法生成根证书,不断弹出

Fiddler中安装证书进行https协议的抓取

Fiddler目前默认安装对http协议进行抓取但是对手机以及其他一些是https协议的通讯抓取需要配置. 首先我们要在fiddler中找到菜单栏的Tools > Options,打开"Options"对话框. 1. 在打开的"HTTPS"选项卡中,勾选"Capture HTTPS  CONNECTs"和"Decrypt HTTPStraffic"前面的复选框 2. 在connections选项卡中,勾选"Al

Mac charles 抓取https请求,安装证书后还是显示unknown

https://blog.csdn.net/qq_23114525/article/details/81460840 1. 配置证书 2. 设置钥匙串信任 3. 设置手机代理 端口号需要对应设置的端口号 4. 手机需要设置证书信任关系 通用->关于本机->证书信任设置(必须勾选上) 5. 可以成功抓取https的请求了 如果出现一部分网站的https可以请求一部分的https不能抓取还是显示unknown,检查一下自己电脑的网络设置,之前我一直不能抓取是因为我的DNS配置错误了 这里的问题是我

MAC配置Charles,过滤筛选抓取https请求(证书安装完毕且设置信任后,https依然为unknown的原因)

MAC安装证书,设置为始终信任 Charles代理信息设置 Charles所在MAC的IP地址查看 手机安装证书 根据下图说明操作 vivo/iphone为例 Android&iphone手机设置代理 ①保证手机同mac连接的同一wifi ②在手机端wifi详情处选择配置代理:手动,IP:mac的IP(即Charles所在MAC的IP地址查看的结果)端口号8888 手机浏览器访问:chls.pro/ssl,下载证书. iphone 在设置——通用——描述文件处安装完毕后,在设置——关于本机——证

fiddler抓取手机端的数据流量包

1.首先下载安装fiddler 2.然后打开fiddler,进入到tools-->options-->connections 3.然后进入到https 4.设置完成后,查找本机ip 然后打开手机的wifi,进行代理设置,手动输入本机ip地址,端口号就是8888 5.最重要的一点就是要手机端安装证书,要不然就会报tunnel to 443,抓取不到https的数据包 6.安装证书步骤 手机浏览器输入:http://你挂代理的ip:8888/FiddlerRoot.cer,然后安装成功就能抓取ht

PHP如何抓取https内容?记录一下。

PHP里做一般的获取内容时,用自带的file_get_contents()函数基本就足够了.当然,这个函数只能抓一些简单的数据,如果是遇到需要登录的页面,就不行了,而且效率及稳定性也不是很强.所以要是有特殊需求的话,还是用curl吧.不仅仅速度快,而且非常稳定,基本上用curl抓取失败的几率很小. 而且今天在抓优酷视频API接口中的信息时,发现了一个问题,由于优酷API的url请求是https安全协议,用file_get_contents()函数竟然无法获取到数据,然后用curl写了个代替函数,

手机通过Charles抓取https包

因为fiddler不能在mac上使用,而Charles是跨平台的,可以在mac上使用,所以需要了解一下Charles的使用 安装破解版Charles 下载破解版包,先启动一次未破解版的Charles,然后再替换包内容的java下的Charles.jar 破解版下载地址(如果不幸的又不能下载了,那就网上随便搜一个吧):http://download.csdn.net/download/m694449212/9770583 手机通过Charles抓取https 第一步:配置Charles,允许抓取h

php分享十八:网页抓取

一.抓取远程图片到本地,你会用什么函数? 方法1:利用readfile读取远程图片到缓冲中,然后写入新的文件 function grabImage($url, $filename = '') { if($url == '') { return false; //如果 $url 为空则返回 false; } $ext_name = strrchr($url, '.'); //获取图片的扩展名 if($ext_name != '.gif' && $ext_name != '.jpg' &

fiddler抓取HTTPS请求

Https即 Http over ssl,使用ssl加密传输数据,Http是明文传输数据的,所以Https必然比Http更安全.即使传输数据被劫持,劫持者也无法获取传输明文.从而保证了系统的安全性,尤其对于交易支付类业务来说,https的安全性尤为重要. 作为测试免不了会使用工具抓取请求,但是fiddler默认置灰抓取http请求,那么如何抓取HTTPS请求呢,下面根据自己的使用总结一下如何使用fiddler抓取HTTPS请求: 前置:fiddler可以抓取http请求 一.fiddler如何抓