21xrx.com
2024-11-05 21:52:49 Tuesday
登录
文章检索 我的文章 写文章
Java如何绕过https证书验证
2023-06-14 20:32:25 深夜i     --     --
Java https 证书验证

在Java中,访问HTTPS网站时需要验证服务器证书以保证安全性。然而,在某些情况下我们可能需要绕过这种证书验证,例如开发调试、测试等环境中。那么,Java如何绕过https证书验证呢?下面有一种简单有效的方法。

示例代码:


import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLSession;

import javax.net.ssl.TrustManager;

import javax.net.ssl.X509TrustManager;

public class HttpsUtil {

  /**

   * 绕过https证书验证

   */

  public static void trustAllHttpsCertificates() throws Exception {

    TrustManager[] trustAllCerts = new TrustManager[1];

    TrustManager tm = new MyTrustManager();

    trustAllCerts[0] = tm;

    SSLContext sc = SSLContext.getInstance("SSL");

    sc.init(null, trustAllCerts, null);

    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

  }

  static class MyTrustManager 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证书验证

   */

  public static void ignoreSsl() {

    try {

      trustAllHttpsCertificates();

      HostnameVerifier hv = new HostnameVerifier() {

        public boolean verify(String urlHostName, SSLSession session) {

          return true;

        }

      };

      HttpsURLConnection.setDefaultHostnameVerifier(hv);

    } catch (Exception e) {

      e.printStackTrace();

    }

  }

}

以上代码实现了一个忽略SSL证书的工具类,其中MyTrustManager类和ignoreSsl方法实现了绕过证书验证的功能。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复