Java TLSv1.3 protocol code example using SSLSocket


Java-TLSv1.3 Example

✌️Oracle Java added support to TLS v1.3 in 8u261-b12 update!

Java has support to TLSv1.3 protocol for Java JDK 1.8 and well supported by JDK 11 and later, this example demonstrates how you can connect to server (http address) using SSLSocket using TLSv1.3 protocol and TLS_AES_128_GCM_SHA256 cipher.

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

/**
 *
 * Example of TLSv1.3 connection
 * This code should work with
 * Java JDK 8 11, 15
 * 
 * Note: Make sure you are using
 * the the JDK version that
 * Supports TLSv1.3
 *
 */
public class TSLv1_3Example {

    private static final String host="code2care.org";
    private static final int port=443;
    private static final String TLSV1_3 = "TLSv1.3";
    private static final String TLS_AES_128_GCM_SHA256 = "TLS_AES_128_GCM_SHA256";
    private static SSLSocket sslSocket;

    public static void main(String... args) throws Exception {

        getSslSocket();
        sendRequest();
        readResponse();

    }

    public static void getSslSocket() throws IOException {

        SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, port);
        
        //Setting the TSLv1.3 protocol
        sslSocket.setEnabledProtocols(new String[]{TLSV1_3});
        
        //Setting the Cipher: TLS_AES_128_GCM_SHA256
        sslSocket.setEnabledCipherSuites(new String[]{TLS_AES_128_GCM_SHA256});
        
        //Handshake
        sslSocket.startHandshake();

    }

    /**
     * Read the sslSocket response
     *
     */
    public static void readResponse() {

        try(BufferedReader in = new BufferedReader(
                new InputStreamReader(
                        sslSocket.getInputStream()))) {

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

        } catch (IOException e) {
            System.out.println("Error occurred while reading Socket Response...");
            e.printStackTrace();
        }
    }

    /**
     *
     * Send Request to sslSocket
     *
     * @throws IOException
     */
    public static void sendRequest() throws IOException {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(sslSocket.getOutputStream());
        PrintWriter printWriter = new PrintWriter(new BufferedWriter(outputStreamWriter));
        printWriter.println("GET /test-url HTTP/1.1\r\n");
        printWriter.flush();
    }
}
Output:
HTTP/1.1 200 OK
Server: code2care.org
Date: Tue, 13 Apr 2021 05:43:25 GMT
Content-Type: text/html
Content-Length: 267
Connection: close


















Copyright Β© Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap