TLS Socket , client & server in NodeJS, The TLS module provides an implementation of the Transport Layer Security (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.

The only major differences between this and a regular TCP connection are the private Key and the public certificate that you’ll have to set into an option object.

How to Create a Key and Certificate

The first step in this security process is the creation of a private Key. And what is this private key?

Private Key:

Basically, it’s a set of random noise that’s used to encrypt information. In theory, you could create one key, and use it to encrypt whatever you want. But it is best practice to have different keys for specific things. Because if someone steals your private key, it’s similar to having someone steal your house keys. Imagine if you used the same key to lock your car, garage, office, etc.

Private keys can be generated in multiple ways. The example below illustrates use of the OpenSSL command-line interface to generate a 1024-bit RSA private key:

openssl genrsa -out private-key.pem 1024

Once we have our private key, we can create a CSR (certificate signing request), which is our request to have the private key signed by a fancy authority. That is why you have to input information related to your company. This information will be seen by the signing authority, and used to verify you. In our case, it doesn’t matter what you type, since in the next step we’re going to sign our certificate ourselves.

The OpenSSL command-line interface can be used to generate a CSR for a private key:

openssl req -new -key private-key.pem -out csr.pem

Now that we have our paper work filled out, it’s time to pretend that we’re a cool signing authority.

openssl x509 -req -in csr.pem -signkey private-key.pem -out public-cert.pem

Now that you have the private key and the public cert, you can establish a secure connection between two NodeJS apps. And, as you can see in the example code, it is a very simple process. Important!

Since we created the public cert ourselves, in all honesty, our certificate is worthless, because we are nobodies. The NodeJS server won’t trust such a certificate by default, and that is why we need to tell it to actually trust our cert with the following option rejectUnauthorized: false. Very important: never set this variable to true in a production environment.

TLS Socket Server

Here is an example of TLS socket server

'use strict'; var tls = require('tls'); var fs = require('fs'); const PORT = 1337; const HOST = '127.0.0.1' var options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem') }; var server = tls.createServer(options, function(socket) { // Send a friendly message socket.write("I am the server sending you a message."); // Print the data that we received socket.on('data', function(data) { console.log('Received: %s [it is %d bytes long]', data.toString().replace(/(

)/gm,""), data.length); }); // Let us know when the transmission is over socket.on('end', function() { console.log('EOT (End Of Transmission)'); }); }); // Start listening on a specific port and address server.listen(PORT, HOST, function() { console.log("I'm listening at %s, on port %s", HOST, PORT); }); // When an error occurs, show it. server.on('error', function(error) { console.error(error); // Close the connection after the error occurred. server.destroy(); });

TLS Socket Client

Here is an example of TLS socket client

'use strict'; var tls = require('tls'); var fs = require('fs'); const PORT = 1337; const HOST = '127.0.0.1' // Pass the certs to the server and let it know to process even unauthorized certs. var options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'), rejectUnauthorized: false }; var client = tls.connect(PORT, HOST, options, function() { // Check if the authorization worked if (client.authorized) { console.log("Connection authorized by a Certificate Authority."); } else { console.log("Connection not authorized: " + client.authorizationError) } // Send a friendly message client.write("I am the client sending you a message."); }); client.on("data", function(data) { console.log('Received: %s [it is %d bytes long]', data.toString().replace(/(

)/gm,""), data.length); // Close the connection after receiving the message client.end(); }); client.on('close', function() { console.log("Connection closed"); }); // When an error ocoures, show it. client.on('error', function(error) { console.error(error); // Close the connection after the error occurred. client.destroy(); });

original publish on Nodefrost.com

Recommended Courses:

☞ Node.js Absolute Beginners Guide - Learn Node From Scratch

☞ Master Full-Stack Web Development | Node, SQL, React, & More

☞ Memory Based Learning Bootcamp: Node.js

☞ Code with Node: Learn by Doing

The only major differences between this and a regular TCP connection are the private Key and the public certificate that you’ll have to set into an option object.

How to Create a Key and Certificate

The first step in this security process is the creation of a private Key. And what is this private key?

Private Key:

Basically, it’s a set of random noise that’s used to encrypt information. In theory, you could create one key, and use it to encrypt whatever you want. But it is best practice to have different keys for specific things. Because if someone steals your private key, it’s similar to having someone steal your house keys. Imagine if you used the same key to lock your car, garage, office, etc.

Private keys can be generated in multiple ways. The example below illustrates use of the OpenSSL command-line interface to generate a 1024-bit RSA private key:

openssl genrsa -out private-key.pem 1024

Once we have our private key, we can create a CSR (certificate signing request), which is our request to have the private key signed by a fancy authority. That is why you have to input information related to your company. This information will be seen by the signing authority, and used to verify you. In our case, it doesn’t matter what you type, since in the next step we’re going to sign our certificate ourselves.

The OpenSSL command-line interface can be used to generate a CSR for a private key:

openssl req -new -key private-key.pem -out csr.pem

Now that we have our paper work filled out, it’s time to pretend that we’re a cool signing authority.

openssl x509 -req -in csr.pem -signkey private-key.pem -out public-cert.pem

Now that you have the private key and the public cert, you can establish a secure connection between two NodeJS apps. And, as you can see in the example code, it is a very simple process. Important!

Since we created the public cert ourselves, in all honesty, our certificate is worthless, because we are nobodies. The NodeJS server won’t trust such a certificate by default, and that is why we need to tell it to actually trust our cert with the following option rejectUnauthorized: false. Very important: never set this variable to true in a production environment.

TLS Socket Server

Here is an example of TLS socket server

'use strict'; var tls = require('tls'); var fs = require('fs'); const PORT = 1337; const HOST = '127.0.0.1' var options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem') }; var server = tls.createServer(options, function(socket) { // Send a friendly message socket.write("I am the server sending you a message."); // Print the data that we received socket.on('data', function(data) { console.log('Received: %s [it is %d bytes long]', data.toString().replace(/(

)/gm,""), data.length); }); // Let us know when the transmission is over socket.on('end', function() { console.log('EOT (End Of Transmission)'); }); }); // Start listening on a specific port and address server.listen(PORT, HOST, function() { console.log("I'm listening at %s, on port %s", HOST, PORT); }); // When an error occurs, show it. server.on('error', function(error) { console.error(error); // Close the connection after the error occurred. server.destroy(); });

TLS Socket Client

Here is an example of TLS socket client

'use strict'; var tls = require('tls'); var fs = require('fs'); const PORT = 1337; const HOST = '127.0.0.1' // Pass the certs to the server and let it know to process even unauthorized certs. var options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'), rejectUnauthorized: false }; var client = tls.connect(PORT, HOST, options, function() { // Check if the authorization worked if (client.authorized) { console.log("Connection authorized by a Certificate Authority."); } else { console.log("Connection not authorized: " + client.authorizationError) } // Send a friendly message client.write("I am the client sending you a message."); }); client.on("data", function(data) { console.log('Received: %s [it is %d bytes long]', data.toString().replace(/(

)/gm,""), data.length); // Close the connection after receiving the message client.end(); }); client.on('close', function() { console.log("Connection closed"); }); // When an error ocoures, show it. client.on('error', function(error) { console.error(error); // Close the connection after the error occurred. client.destroy(); });

original publish on Nodefrost.com

Recommended Courses:

☞ Node.js Absolute Beginners Guide - Learn Node From Scratch

☞ Master Full-Stack Web Development | Node, SQL, React, & More

☞ Memory Based Learning Bootcamp: Node.js

☞ Code with Node: Learn by Doing

node-js nodejs node javascript