iT邦幫忙

0

Java 實現自帶的 X509TrustManger 介面,忽略證書驗證過程,忽略之後任何 https 網站皆能正常訪問。

  • 分享至 

  • xImage
  •  
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * @author 
 *
 */
public class MyX509TrustManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] chain,
        String authType)
            throws CertificateException {
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain,
        String authType)
            throws CertificateException {
    }

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

    /**
     * 測試
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        String urlString = "";

        URL url = new URL(urlString);
        HttpsURLConnection httpsConn =
            (HttpsURLConnection) url.openConnection();

        TrustManager[] tm = {new MyX509TrustManager()};
        // 建立 SSLContext
        SSLContext sc = SSLContext.getInstance("TLSv1.2");
        // 初始化 SSLContext
        sc.init(null, tm, new java.security.SecureRandom());
        // 獲取 SSLSocketFactory 物件
        SSLSocketFactory ssf = sc.getSocketFactory();
        // 設定當前使用的 SSLSoctetFactory
        httpsConn.setSSLSocketFactory(ssf);
    }
}

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言