unable to find valid certification path to requested target

问题描述:JVM信任库中找不到安全证书导致获取url资源时产生安全性问题

        因为业务场景的需求,需要通过图片URL获取二进制流,在读取时遇到一个安全证书问题。如果这个图片或文件走的是https协议,会涉及到安全敏感问题,在代码中发起普通的http请求会产生请求安全性异常,报错信息如下:

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

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

        随后在网上找了很多资料,发现大多数的解决方式都是生成一个安全证书再放到jre中进行初始化读取,但我尝试了很多种读取方式依旧无效。后来发现其实jdk对ssl就有现成的打开方式 

解决方法:

        1.定义信任管理器的实现类

import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author jk
 */
public class MyX509TrustManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}

         2.使用ssl上下文进行初始化

HTTPS实际上是HTTP的安全版(即HTTP下加入SSL层),HTTPS的安全基础是SSL,因此加密的详细内容就需要SSL。

 public static InputStream getHttpsFile(String fileUrl) throws NoSuchProviderException, NoSuchAlgorithmException, IOException, KeyManagementException {
        // https -- 创建SSLContext对象,使用指定的信任管理器初始化
        if (fileUrl.contains("https:")) {//https
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(fileUrl);
            HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
            httpsConn.setSSLSocketFactory(ssf);
            httpsConn.setDoInput(true);
            httpsConn.setDoOutput(true);
            return httpsConn.getInputStream();
            //http
        } else {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10 * 1000);
            return connection.getInputStream();
        }
    }

对你有帮助的话,点个赞支持一下吧!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值