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.




No comments:

Post a Comment