package com.jeelowcode.service.system.util;

import lombok.SneakyThrows;

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

/**
 * Description: SSH工具类
 * Author: Shelly Chan
 * Date: 2023/1/31 10:05
 */
public class SshUtils {

    /**
     * 创建信任所有证书的SSLSocketFactory
     */
    @SneakyThrows
    public static SSLSocketFactory createTrustAllSSLFactory() {
        // 1. 创建信任所有证书的TrustManager
        X509TrustManager trustAllCerts = new 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 new X509Certificate[0];
            }
        };

        // 2. 初始化SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[]{trustAllCerts}, new java.security.SecureRandom());

        // 3. 获取SSLSocketFactory
        return sslContext.getSocketFactory();
    }

    /**
     * 配置全局信任所有证书（影响所有HttpsURLConnection请求）
     */
    public static void trustAllCertificatesGlobally() throws Exception {
        HttpsURLConnection.setDefaultSSLSocketFactory(createTrustAllSSLFactory());
        HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
    }

}
