Showing posts with label encryption. Show all posts
Showing posts with label encryption. Show all posts

Thursday, December 5, 2019

SSL/TLS handshake and Java



SSL (Secure Socket Layer) was first released in 1999. It was deprecated since Java 8u31 and renamed to TLS (Transaction Layer Security) due to its deficiency in handling padding attacks, it checks only the padding length but not the value.

TLS has two subprotocols: Handshake and Record Protocol.

The Handshake process establishes the common cryptographic parameters such as the encryption protocol and cipher to be used by both the server and the client.

The Record Protocol defines the rule for breaking down the data into blocks (packets), encrypt and decrypt them.

During  handshaking, the client sends to the server the protocol and ciphers it supports. The server then chooses the protocol and the cipher to be used. The server has a list of supported ciphers and chooses the first one in priority supported by the client. If there is no cipher in common, the handshake fails. The protocol and cipher are suggested by client but chosen by the server.

An SSL/TLS connection succeeds only if the client trusts the server. After the protocol and cipher are chosen, the server sends the client its certificate. The client will trust the server only if it can trace the certificate to a root certificate, which is known as chain validation. 

Then, the server and the client exchange their public keys and generate the session key or master key. If the ending messages of the handshaking are successfully encrypted and decrypted by both sides, the handshaking is complete.

Since Java 8u151, the Java Cryptography extension, JCE, is bundled in the JDK. Java JCE is a framework for encryption, key generation, key agreement and message authentication code (MAC). 

From Java 8 onward, the default encryption protocol version is TLSv1.2 which is backward compatible. 

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.




Wednesday, December 4, 2019

SSL/TLS: Use a self-signed certificate in Java client for secure socket connection

A certificate not issued by any known Certificate Authorities (CA) but rather by the server hosting the certificate is a self-signed certificate. The root certificate for such a self-signed certificate is absent in the client's certificate store, which causes the chain validation failure.

After receiving your self-signed certificate mycert.crt, follow these steps to create your java client.

1. Import the self-signed certificate into your java truststore.

Your java truststore, cacerts, is located in $JAVA_HOME/jre/lib/security. Copy the cacerts to the location you want it to be. The password of the truststore is changeit

The cacerts bundled with the java JDK contains the root certificates for Certificate Authorities (CA) that issue certificates such as GoDaddy, Verisign, Network Solutions, and others. We will need these root certificates to establish the trust between the client and the server.

Open the Command Prompt and use the following command to import the mycert.crt into the cacerts truststore.

       keytool -import -v -trustcacerts -file mycert.crt -alias mycert -keystore cacerts
 
       Enter keystore password: changeit
     
       . . . . . .

       Trust this certificate? [no]: yes
       Certificate was added to keystore
       [Storing cacerts]

2. Create the java client using the truststore

public class TLSClient {

    public static void main(String[] args) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException {

        System.setProperty("javax.net.ssl.trustStore", "cacerts");
        System.setProperty("javax.net.ssl.keyStorePassword", "changeit");

        out.println("Load the keystore...");
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

        try (FileInputStream readCert = new FileInputStream("./cacerts")) {
            ks.load(readCert, "changeit".toCharArray());
        }

        out.println("Initialize the KeyManagerFactory...");
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, "changeit".toCharArray());

        out.println("Create a trust manager...");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(
               TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);

        //Initialize the SSLContext
        out.println("Get the SSLContext...");
        SSLContext sc = SSLContext.getInstance("TLS");

        out.println("Initialize the SSLContext...");
        sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        out.println("create socket...");
        SSLSocketFactory factory = sc.getSocketFactory();
        try(SSLSocket clientSocket = (SSLSocket) factory.createSocket(getByName("<server IP address>"), <server port>)){

            //debug
            SSLSession session = clientSocket.getSession();
            Certificate[] cchain = session.getPeerCertificates();
            out.println("The Certificates used by peer");
            for (Certificate cchain1 : cchain) {
                out.println(((X509Certificate) cchain1).getSubjectDN());
            }
            out.println("Peer host is " + session.getPeerHost());
            out.println("Cipher is " + session.getCipherSuite());
            out.println("Protocol is " + session.getProtocol());
            out.println("ID is " + new BigInteger(session.getId()));
            out.println("Session created in " + session.getCreationTime());
            out.println("Session accessed in " + session.getLastAccessedTime());
            //finish debug

            out.println("Sucessfully connected!!!");
            //Use the clientSocket to communicate with the server now
        }
    }
}

If the code executes fine, it prints the output below:

Load the keystore...
Initialize the KeyManagerFactory...
Create a trust manager...
Get the SSLContext...
Initialize the SSLContext...
create socket...
The Certificates used by peer
O=Default Company Ltd, L=Default City, C=XX
Peer host is <server IP address>
Cipher is TLS_RSA_WITH_AES_256_CBC_SHA256
Protocol is TLSv1.2
ID is -20222101607659081628530787401436194355856927161855171792439103526019628250528
Session created in 1575480427055
Session accessed in 1575480427235
Sucessfully connected!!!
           
-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.




Thursday, November 21, 2019

javax.net.ssl.SSLException: Unsupported record version Unknown-0.20

After you started your server and client are connected, you try to read data and you see the following exception.

javax.net.ssl.SSLException: Unsupported record version Unknown-0.20
        at sun.security.ssl.InputRecord.checkRecordVersion(InputRecord.java:552)
        at sun.security.ssl.InputRecord.readV3Record(InputRecord.java:565)
        at sun.security.ssl.InputRecord.read(InputRecord.java:529)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:975)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
        at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:931)
        at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)

To fix this exception:

1. Check if both the server and the client are connecting through SSL/TLS. If one end is using SSL/TLS and the other side is not, it will throw such an exception.

2. Make sure that both sides are using the same encryption protocol such as TLSv1, TLSv1.1, TLSv1.2,  or SSLv3. When you transmit using an SSL/TLS Socket, it calls a formatting and encryption routine to create the encrypted packet. It then calls the plain sockets layer to transfer the encrypted packet to the server. The server's sockets layer receives the packet and then calls the SSL/TLS package to decrypt the packet. If the packet doesn't fit the SSL/TLS format, you get the unsupported version exception.

3. The version of java you are using supports the encryption protocol.

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.