Java SSLSocket TLS 1.3示例

这篇博客介绍了如何在Java 11中使用SSLSocket实现TLS 1.3协议,包括一个客户端示例,用于连接到https://google.com并打印响应。内容引用了Oracle的相关资源和JEP 332,提供了源代码下载链接。
摘要由CSDN通过智能技术生成

该Java 11 JEP 332添加了对TLS 1.3协议的支持。

SSLSocket + TLS 1.3

具有TLS1.3协议和TLS_AES_128_GCM_SHA256流密码的SSLSocket客户端,用于将请求发送到https://google.com并打印响应。

JavaTLS13.java
package com.mkyong.java11.jep332;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;

// Java 11
public class JavaTLS13 {

    private static final String[] protocols = new String[]{"TLSv1.3"};
    private static final String[] cipher_suites = new String[]{"TLS_AES_128_GCM_SHA256"};

    public static void main(String[] args) throws Exception {

        SSLSocket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            SSLSocketFactory factory =
                    (SSLSocketFactory) SSLSocketFactory.getDefault();
            socket =
                    (SSLSocket) factory.createSocket("google.com", 443);

            socket.setEnabledProtocols(protocols);
            socket.setEnabledCipherSuites(cipher_suites);

            socket.startHandshake();

            out = new PrintWriter(
                    new BufferedWriter(
                            new OutputStreamWriter(
                                    socket.getOutputStream())));

            out.println("GET / HTTP/1.0");
            out.println();
            out.flush();

            if (out.checkError())
                System.out.println("SSLSocketClient:  java.io.PrintWriter error");

            /* read response */
            in = new BufferedReader(
                    new InputStreamReader(
                            socket.getInputStream()));

            String inputLine;
            while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socket != null)
                socket.close();
            if (out != null)
                out.close();
            if (in != null)
                in.close();
        }
    }

}

输出量

Terminal
HTTP/1.0 200 OK
Date: Fri, 15 May 2020 13:24:25 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
Server: gws
X-XSS-Protection: 0

//...

上面的源代码是此Oracle – Running SSLSocketClient文章的副本,并进行了少量修改以支持TLS 1.3。

下载源代码

$ git clone https://github.com/mkyong/core-java

$ cd java-11

参考文献

翻译自: https://mkyong.com/java/java-sslsocket-tls-1-3-example/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值