该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/