Java SSLSocket TLS 1.3 example
This Java 11 JEP 332 adds support for TLS 1.3 protocol.
SSLSocket + TLS 1.3
An SSLSocket
client with TLS1.3
protocol and TLS_AES_128_GCM_SHA256
stream cipher, to send a request to https://google.com and print the response.
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();
}
}
}
Output
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
//...
The above source code is a copy from this Oracle – Running SSLSocketClient article, with minor modifications to support TLS 1.3.
Download Source Code
$ git clone https://github.com/mkyong/core-java
$ cd java-11
References
About Author
Comments
Subscribe
0 Comments