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? 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.
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.
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 followingoption rejectUnauthorized: false
. Very important: never set this variable to true in a production environment.
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(/(\n)/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
'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(/(\n)/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();
});
With all that being said, I highly recommend you keep learning!
Thank you for reading this article. Please feel free to connect with me on LinkedIn and Twitter.