http忽略ssl认证

本文详细介绍了如何在Java中使用ApacheHttpClient和URLConnection忽略SSL证书验证,包括创建自定义TrustManager、SSLContext和SSLConnectionSocketFactory,以及使用NoopHostnameVerifier来处理HTTPS请求的SSL证书问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们在发请求时,会遇到需要ssl证书验证的报错,针对该错误以及所使用的不同的创建连接的方式,进行ssl证书忽略

忽略SSL证书的流程

简介:需要告诉client使用一个不同的TrustManager。TrustManager是一个检查给定的证书是否有效的类。SSL使用的模式是X.509,对于该模式Java有一个特定的TrustManager,称为X509TrustManager。首先我们需要创建这样的TrustManager。将TrustManager设置到我们的HttpClient。TrustManager只是被SSL的Socket所使用。Socket通过SocketFactory创建。对于SSL Socket,有一个SSLSocketFactory。当创建新的SSLSocketFactory时,你需要传入SSLContext到它的构造方法中。在SSLContext中,我们将包含我们新创建的TrustManager。

  1. 创建的TrustManager
  2. 创建SSLContext:TLS是SSL的继承者,但是它们使用相同的SSLContext。
  3. 创建SSLSocketFactory
  4. 将SSLSocketFactory注册到我们的HttpClient上。这是在SchemeRegistry中完成的。
  5. 创建ClientConnectionManager,创建SchemeRegistry。
  6. 生成HttpClient

http忽略ssl认证

忽略https认证,就是自己构建一个x509认证,默认通过,再传到ssl配置工厂中

1. httpClient忽略ssl证书连接

client发起请求时,使用已经构建过认证client发起请求

package com.neo.address.parse;

/**
 * @author caoying
 * @since 2024/4/14
 */

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

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

public class WebTool2 {
    public static void main(String[] args) {
        //
        String url = "https://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023/";
        try {
            String html = fetchPageContent(url);
            List<String> provinces = extractDataByTag(html, "tr", "provincetr");
            List<String> cities = extractDataByTag(html, "tr", "citytr");
            List<String> counties = extractDataByTag(html, "tr", "countytr");
            List<String> towns = extractDataByTag(html, "tr", "towntr");

            // 输出提取的数据
            System.out.println("Provinces: " + provinces);
            System.out.println("Cities: " + cities);
            System.out.println("Counties: " + counties);
            System.out.println("Towns: " + towns);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String fetchPageContent(String url) throws IOException {

//        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpGet request = new HttpGet(url);

        try {
                //忽略https的ssl认证
            //发起请求 , 调用trustAll()方法返回的client
            HttpEntity entity = trustAll().execute(request).getEntity();
            return EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
//            httpClient.close();
        }
    }

    private static List<String> extractDataByTag(String html, String tagName, String className) {
        List<String> dataList = new ArrayList<>();
        Document doc = Jsoup.parse(html);
        Elements elements = doc.select(String.format(".%s", className));
        for (Element element : elements) {
            String data = element.select(tagName).text();
            dataList.add(data);
        }
        return dataList;
    }

    public static CloseableHttpClient trustAll(){
        //配置,发送https请求时,忽略ssl证书认证(否则会报错没有证书)
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }

//创建httpClient
        CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();

        return client;
    }
}

2. urlconnection忽略ssl证书连接

忽略HTTPS请求的SSL证书,必须在openConnection之前调用

package com.neo.address.parse;

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

/**
 * Description: httpclient跳过https验证
 */

import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import org.apache.commons.io.IOUtils;

/**
 * created by liu on 2020/03/18 14:23
 */

public class SslUtil {
    private static void trustAllHttpsCertificates() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    static class miTM implements TrustManager, X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }
    }

    /**
     * 忽略HTTPS请求的SSL证书,必须在openConnection之前调用
     *
     * @throws Exception
     */
    public static void ignoreSsl() throws Exception {
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                System.out.println("Warning: URL Host: " + urlHostName
                        + " vs. " + session.getPeerHost());
                return true;
            }
        };
        trustAllHttpsCertificates();
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }
}

 

<think>嗯,用户现在问的是如何忽略SSL证书认证。之前他们问的是怎么实现安全的HTTPS开发环境,我给了详细的步骤,包括生成自签名证书、配置服务端和客户端,以及证书管理优化方案。现在这个问题看起来有些相反,用户可能想快速绕过证书验证,可能在开发测试阶段遇到证书问题,想要快速解决。 首先,我需要确认用户的场景。他们可能是在开发环境中遇到了自签名证书不被信任的问题,或者测试时使用无效证书的服务,导致请求失败。这时候,忽略证书验证可能是一个临时解决方案。但必须提醒用户这是不安全的,只能用于开发测试,不能在生产环境中使用。 接下来,我需要考虑用户可能的真实需求。他们可能希望快速解决问题,但作为负责任的回答,必须强调安全风险。用户可能不知道忽略证书的风险,或者觉得配置证书麻烦,所以需要给出替代方案,比如之前提到的自签名证书方法,并对比两者的优缺点。 然后,我要整理不同语言和工具中忽略证书验证的方法。比如在Java、Python、Node.js、curl、Postman等常见环境中如何操作。每个部分需要简明扼要,给出代码示例,同时警告风险。 同时,用户可能对某些具体环境更感兴趣,比如他们主要用Java或Python,所以需要分门别类,方便查找。此外,还要提到前一个回答中的安全方案,引导用户采用更安全的方法,即使稍微麻烦一些。 最后,需要总结强烈建议仅在开发环境使用,并推荐更安全的替代方案。可能用户之前已经看过安全方案,但觉得麻烦,所以现在想找捷径。这时候需要平衡快速解决方案和安全建议,确保用户理解风险。</think>以下是针对忽略SSL证书认证的 **安全风险说明与开发环境解决方案**,请特别注意安全警告: --- ### 一、核心原理说明 ```mermaid flowchart LR A[客户端] -->|1.发起HTTPS请求| B(服务端) B -->|2.返回证书| A A -->|3.强制信任所有证书| C[建立不安全连接] ``` ⚠️ 该操作会 **完全关闭SSL验证机制**,导致: - 中间人攻击风险 - 数据明文传输风险 - 服务器身份无法验证 --- ### 二、各语言实现方式(仅限开发测试) #### ▨ Java方案 ```java // 创建不验证证书的TrustManager TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) {} public void checkServerTrusted(X509Certificate[] chain, String authType) {} public X509Certificate[] getAcceptedIssuers() { return null; } } }; // 创建SSL上下文 SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); // 应用全局配置(危险操作!) HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true); ``` #### ▨ Python方案 ```python import ssl import requests # 禁用证书验证(仅限测试) response = requests.get("https://example.com", verify=False) # 完全关闭验证(极端危险) ssl._create_default_https_context = ssl._create_unverified_context ``` #### ▨ Node.js方案 ```javascript // 在请求参数中添加 process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; // 或针对单个请求 const https = require('https'); const agent = new https.Agent({ rejectUnauthorized: false }); ``` --- ### 三、常用工具配置 #### ▨ Curl跳过验证 ```bash curl -k https://insecure-domain.com # --insecure 的简写 ``` #### ▨ Postman设置 1. File → Settings → General → 关闭 _"SSL certificate verification"_ 2. 发送请求时Header添加: ```http Postman-Token: <随机UUID> ``` --- ### 四、更安全的替代方案(推荐) ```diff - 直接关闭证书验证(高风险) + 通过以下方式实现安全开发: 1. 创建自签名证书(前文方案) 2. 将证书导入系统信任库 3. 使用本地DNS绑定(hosts文件) 4. 配置开发环境专用CA证书 ``` --- ### 五、最佳实践建议 1. **隔离环境**:仅在独立的开发/测试网络中使用 2. **代码隔离**:使用环境变量控制验证逻辑 ```java if ("prod".equals(System.getenv("APP_ENV"))) { // 启用严格验证 } else { // 开发环境特殊处理 } ``` 3. **自动清理**:通过pre-commit hook防止误提交 ```bash # Git预提交检查 grep -R "setDefaultHostnameVerifier" src/ && exit 1 ``` --- 请务必注意:这些方法 **只能用于本地开发环境**,在生产环境中使用会导致系统面临严重安全风险。建议优先采用前文所述的自签名证书方案。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值