jdk8支持TLSv1.3协议有版本的限制

package com.example.cloud.utils;
import org.openjsse.net.ssl.OpenJSSE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.Arrays;

public class TslUtil {
    private static final Logger LOG = LoggerFactory.getLogger(TslUtil.class);
    public static void main(String[] args) throws Exception {
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, null, new SecureRandom());
        LOG.info("支持的协议版本:{}", Arrays.toString(context.getSocketFactory().getSupportedCipherSuites()));
        testUrlService();
    }
    public static void testUrlService() throws Exception {
        Security.addProvider(new OpenJSSE());
        SSLContext sslContext = SSLContext.getInstance("TLSv1.3");
        X509TrustManager x509TrustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
            }

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

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

        sslContext.init(null, new TrustManager[]{x509TrustManager}, new java.security.SecureRandom());
       // SSLParameters sslParams = new SSLParameters();
       // sslParams.setCipherSuites(new String[]{"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA"});
       // sslContext.getDefaultSSLParameters().setCipherSuites(sslParams.getCipherSuites());
        String[] cipherSuites = new String[]{
                "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
                "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
        
        };
       // sslContext.getDefaultSSLParameters().setCipherSuites(cipherSuites);
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
       boolean contain =  Arrays.asList(sslSocketFactory.getSupportedCipherSuites()).contains("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384");
        LOG.error(String.valueOf(contain));
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        final String json = "";
        String postData = json;
        String url = "";
        HttpsURLConnection conn;
        OutputStream out = null;
        String response;
        byte[] byteArray = postData.getBytes(StandardCharsets.UTF_8);
        try {
            URL uri = new URL(url); 
            conn = (HttpsURLConnection) uri.openConnection();
            conn.setHostnameVerifier((hostname, session) -> true);
            conn.setRequestMethod("POST"); 
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Host", uri.getHost());
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Connection", "keep-alive");
            out = conn.getOutputStream();
            out.write(byteArray);
            out.flush();
            if (conn.getResponseCode() == 200) {
                response = getStreamAsString(conn.getInputStream(), "utf-8");
            } else {
                response = getStreamAsString(conn.getErrorStream(), "utf-8");
            }
            LOG.info(response);
        } catch (Exception e) {
            LOG.info("出现异常", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    private static String getStreamAsString(InputStream stream, String charset) throws IOException {
        if (stream == null || charset == null) {
            throw new IllegalArgumentException("InputStream or charset cannot be null");
        }
        try (Reader reader = new InputStreamReader(stream, charset);
             StringWriter response = new StringWriter()) {
            char[] buff = new char[1024];
            int read;
            while ((read = reader.read(buff)) != -1) {
                response.write(buff, 0, read);
            }
            return response.toString();
        }
    }

    /**
     * A HostnameVerifier that bypasses the standard hostname verification.
     * WARNING: This should only be used in trusted environments for testing purposes.
     */
    public class BypassHostnameVerifier implements HostnameVerifier {
        /**
         * Verifies the hostname by bypassing the SSL session's hostname verification.
         *
         * @param hostname the host to verify
         * @param session  the SSL session
         * @return true to always trust the hostname, false otherwise
         */
        @Override
        public boolean verify(String hostname, SSLSession session) {
            // WARNING: This method disables host verification and should be used carefully.
            return true; // Always return true to trust any hostname
        }
    }


}
上一篇:C++多线程编程入门教程(优质版)


下一篇:【ubuntu24.04.1最简洁安装方案】