Encrypted Client-server communication using Nodejs TLS module and OpenSSL

TaDaaaaaaaaaaaaaaaaaaaaaaa !!!!!!!! After meddling with the readers mind in my attempt to get into the source of NodeJS in the last and its previous post , i decided to take it easy on the readers in this blog post 😛 So this post is on using the TLS module from the application layer . Lets see how to securely communicate using the TLS module and OPENSSL .Sounds interesting ?? We’ll , then read on 😀

“What do you mean by a secure communication ???”

In this case im talking about encrypting the message and sending it to other parties so that even if your data is captured by other parties its wont be readable .

Hmmm,Ok , then you gotto decrypt it back at the other end to be able to interpret it right ??

Thats right …. Thats obvious right ? If the data is sent encrypted from one end , it has to be decrypted at the other end to be able to read the information .

So there are 2 questions that has to be answered now ..

1.How do i Encrypt the message ??

2.How do i decrypt the message ???

drrrrrrrrrrrrrrrrrr, Now , How do you think you can achieve this ????

HMMMMMM…….. “Can i use some sort of Encryption-decryption algorithm ????”

You got it right , You use some algorithm to encrypt your message and send it across and then using the reversal of the algorithm it can be decrypted .

“But , isnt this risky? What if someone could understand my algorithm , or crack my Algorithm and decrypt my message ??”

Welllllllll ,here is a secret …………….. “This had happened during the Second World War …” shhhhhhhhhhhhhhhhhhhhhhhhh 😛

Then whats the way out ??


Here is how two parties in communication use Public Key Encryption secure the message exchanged between them .

1.How to Encrypt the message in Public Key Encryption ?

In Public key Encryption both parties have a private-key and public-key with them . Private key remains exclusive to both the parties and they dont share it with anyone . But the public key used exchanged with any other party with the communciation and information exchange takes place .
Lets say X and Y are the 2 parties who now are intending to have a secure encrypted communication using Public key encryption method .

How does X encrypt the message to send it to Y .
– For X to Encrypt a message for the purpose it to Y , X needs to use its own private key (Y too has its own private key) and Y’s public key .

Hmmm, this sounds cool , But since X sends the message encrypted , how will Y decrypt it ???
– For Y to decrypt X’s message it needs its own private key and X’s public key .

You might be wondering now , “Lol !!! Now private key and public key story sounds cool , but how to create one of these ??”


OPENSSL executable comes bundled with most of the popular Linux Distributions and it offers wide range cryptography methods . TLS module uses OPENSSL libraries under the hood . Here is the command to create Private Keys using OpenSSL

 openssl genrsa -out private-key.pem 1024

This creates a private key by name private-key.pem

Public keys are also called as certificates . They are called so because public keys will contain digital signatures which are used to identify the right peer/server.
The certificate can be self signed or it can be signed from certification authorities (As in case of HTTPS sites) . Lets see how to create a self signed public key (self signed certificate) using OPENSSL .
First you gotto create a Certificate Signing Request file using your private key:

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

Then you can create a self-signed certificate, using your private key:

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

“HaHaHa , The certificate Saga was pretty , but certificates are used to just encrypt the data during communication between two parties , but how can i communicate by just using the certificates ?? 😛 “
Well , thats right … Now you gotto create a server and a client which uses these certificate and communicate securely using public key encryption.
Here is the code for the TLS server

 var tls = require('tls'),
    fs = require('fs'),
    colors = require('colors'),
    msg = [
            "#######  ####    ####### ######  ####### ",
    "##    # #     # #     # #             # #     #",
    "# #   # #     # #     # #             # #",
    "#  #  # #     # #     # #####         #  #####",
    "#   # # #     # #     # #       #     #       #",
    "#    ## #     # #     # #       #     # #     #",
    "#     # ####### ######  #######  #####   #####"


var options = {
  key: fs.readFileSync('private-key.pem'),
  cert: fs.readFileSync('public-cert.pem')

tls.createServer(options, function (s) {

Run the code in the folder where you have created your certificates . Here is the link .
The server writes out the message string [msg] to the client when requested , The difference here is that when the message is being transmitted it is encrypted and sent .

 node tls-server.js   

Once the server is running open another terminal

USING OPENSSL to securely communicate with the TLS server

$ openssl s_client -connect

You can now see the screen with the message array [msg] being sent to the OPENSSL client

Open ssl client
Open ssl client

“Nice story on encryption using Node and OPENSSL, but whats the proof that the data is being encrypted and sent to the client ??”

Use Wireshark and check it out for yourself . Here is the screenshot from wireshark after capturing the communciation between the TLs server and the Open SSL client

Encrypted data
Encrypted data

Wireshark clearly shows that the data transmitted is encrypted . Try writing a simple TCP client-server socket program using NodeJS and then capture the dat using wireshark and the data communicated will be directly visible in wireshark inside the captured packets .

Thats it for now !! Ufffffffffffff!!! I shall get into the more details of source of TLS module in the further posts to come . Till then , Happy coding 😀


Preparing to land on C++ core of NodeJS: Sharpening the weapons – Using C++ Templates

Ahhhhhhhhhhhhhhh!!!!!! Travelling 700Kms without music or books on Technology is so pissing off!!!!This is what i call as “Throw away your frustration blog”  😛 😛 Enough !!!!
In the last blog i started out the series on Peeking into the Source code of node.Js .And also i promised to get into the C++ core of NodeJs while i had restricted myself to the
top most layer of node , that is the Javascript layer of it , dont remember ?? :PThen take a look at this .
So you might be thinking now “Yaay, its now time to start with the C++ core of NodeJs”….But when i started out with the defination of GetCIphers() of the TLS node module inside the C++ core ,the C++ lines of code written were just mindblowing. If you check the lines between 4807-4823 in this link from source of node you’ll understand C++ sophistication that lies beneath. It was important to get back to few important C++ concepts before landing on the C++ core of Node.So this post is on Preparing to land on NodeJs C++ Core..To be precise get Ready for a glimpse on C++ Templates and meddling around with them .C++ templates are widely used within the NodeJs core , so its vital to understand them thoroughly

Being into Hardcore Javascript development from past 15 months the term “template” reminds me of ReactJs , AngularJs Templates ,Jade , EJS ,Handle bars and Underscore Templates .Like Templates in Javascript libraries are used to generate dynamic html ,templates in C++ are used to write “generic programs ” where in the same piece of code can deal with variety of datatypes .

Still confused ??? Ill illustrate an example Lets say your are building a class which provides all the functionalities of a calculator .
Here is the link for the code on github .You can execute the code with cloud C++ IDE by clicking on this link

#include <iostream>
using namespace std;
class calculator {
		int add(int x,int y);
		int multiply(int x,int y);

int calculator::add(int x,int y){
	return x+y;

int calculator::multiply(int x,int y){
	return x*y;
int main(){
    calculator instance;

So whats the issue here.
You can clearly see that the member functions Add and Multiply of the class Calculator
can work only on integer datatypes. They return int , the add take int values as
their parameters .
What if this decision on the data type to be worked upon could have made dynamic ??
What if the a same piece of code can dynamically make the same piece of code work for
various datatypes . Yes , its possible by the use of C++ class templates.
By using C++ class templates any given member function can be made flexible enought to be
able to work on various datatypes . Here is how to do it .Here is the implementation using
C++ template classes .
Here is the link of the code on Github.Click here to execute the same code using online C++ editor

template <typename Type> class calcultor{
		Type multiply(Type x,Type y);
		Type add(Type x,Type y);

template <typename Type> Type calc<Type>::add(Type x,Type y)
	return x+y;

template <typename Type> Type calc<Type>::multiply(Type x,Type y)
	return x*y;

calcultor <int> instance1;
claculator <double> instance2;

baffled ??? 😛
Here is the detailed explanation ,

template <typename Type> class calculator {}

is the declaration of the template class , here template and typename are the keywords and
this should be followed after the typename keyword , a placeholder name has to be given
to the variable datatypes that is sent during the creation of the object of the template class.
but it has to be made sure that the same placeholder name has to be used to refer to the
datatype in its member function .

Type multiply(Type x,Type y);

by using this declaration the return type and the parameters of the member functions are also
made dynamic and are ot predefined like it is in the first case .

this is the format for writing the defination for the member functions of a template class .

template <typename [namespace]> return_type parent_class<[namespace]>::member_function(parameters);

and Both the parameters and return Type can itself be dynamic template varialbles (as it is the case
the template class code example )

now while creating the new instance of the object you have the freedom to choose and set the
datatype on which the member functions process upon .

calculator <int> instance1; 

Now the ‘Type’ will be set to int , so this is equivaluent to

class calculator {
		int add(int x,int y);
		int multiply(int x,int y);


int calculator::add(int x,int y){
	return x+y;

int calculator::multiply(int x,int y){
	return x*y;

now ,

calculator <double> instace2;

this is equivalent to

class calculator {
		double add(double x,double y);
		double multiply(double x,double y);


double calculator::add(double x,double y){
	return x+y;

double calculator::multiply(double x,double y){
	return x*y;

The same analogy can be applied to create functions templates .It is illustrated in the code below .

Here is the link of the code on GitHub .Click here to execute the code online.

#include <iostream>
#include <typeinfo>
using namespace std;
template <typename Type> void test_template(Type x){
    cout << x <<endl;
    cout << typeid(Type).name() << endl;
int main()
   return 0;

More Meddling with Class templates

Using class templates as function arguments parameters

Here is a piece of code where Template classes are sent as arguments , the comments give a clear explanation on the syntax.Here is the link of the code on Github.Click here to execute the code on Cloud IDE.

#include <iostream>

template<class Type>
class Other {
    	Type x;
    	Other(Type y){
        	x = y;

    void first(const Other<int>& o) {/*One way of specifying the formal parameter*/
    	std::cout << o.x << '\n';

    template<typename T> void second(const Other<T>& o) {/*Other way of specifyin formal parameter*/
    	/*Has to be decalred as templated function*/
        std::cout << o.x << '\n';

int main(){
    Other<int> other(123);/*initializing template class constructor*/
    first(other);/*sending templated class as parameters*/

Now you know how template classes are sent as function parameters and how the actual and formal parameters are defined .
The C++ core of NodeJs contains magnificent pieces of C++ writing and its very essential to have a strong hold of C++ to be able to comprehend the lines written and this blog was an attempt at helping you guys achieve it .We are Getting closer and closer to land on the planet on NodeJs C++ core ….Its just matter of time !!!
Till then …………….As Usual , Happy Coding 😀

Installing/setting up Neo4j/Cipher-query-terminal in ubuntu

Fascinated by the world of Graphs??Ever wondered how to install/setup the popular graphDB neo4j and the local console to execute your cipher queries (The Graph DB queries) ??If so , read on 😀

Neo4j provides webconsole to execute queries at console.neo4j.org , but you need to have it installed on your local machines to test things out during development(There are drivers available to use neo4j using almost all popular languages). This is a short post describing the setting up of the popular graphDb neo4j in ubuntu
Step-1: Setup Oracle 7
Neo4j needs JVM (its java based) , setup Oracle Java 7 which is a dependency to run Neo4J ,here are the set of instructions to execute from the terminal to setup Oracle Java 7

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer
sudo apt-get install oracle-java7-set-default

Step-2: Download and extract Neo4J
Download  extract Neo4j server  from Neo4j-server-Download and extract it


Step-3:Run the Neo4j server
Go to the extracted folder nd execute the following commands to setup neo4j

cd bin
sudo ./neo4j-installer install
./neo4j start

This starts the Neo4j server on the default port 7474

step-4:Go to browser and checkout localhost:7474
Once the Neo4J server is running,Open you browser and visit localhost:7474 , here is the screenshot

Neo web interface running locally
Neo web interface running locally

Step-5:Execute the cipher queries
Now using the browser interface you can easily execute the cipher queries agianst the Neo4J server running locally

Local cipher
Local cipher

In case you want to use the command line shell to exeute cipher-queries just shell the neo4j-shell , from the /bin start the neo4j-shell

cd bin

tadaaaaaaaaaaaa!!The cipher-query shell opens And start executing the cipher queries 🙂 Here is the screenshot


Welllllllll , this is th end of the post , i hope that this post helped you guys setup neo4j and cypher-query-console on your machines and get started.There will be series of posts coming up soon on using neo4j alongside NodeJs server , till then Happy coding 😀

Sending GET ,POST requests to the server using Backbone.JS and handling them using Node.JS server in the backend

In the last post i discussed about  communicating with the webServer from the browser in the front end using WebSockets .This post too is about sending requests (GET , POST) to the web-server from the browser , but i’ll be employing a different methodology this time around .

So , You might be very curious now about the methodology i’ve employed to interact with the server in this post 😯 😀

In this post  ill be discussing about sending requests to the Node.JS server using Backbone.JS in the front end , Backbone.JS sends AJAX requests to the server.

Backbone.JS is a front end Javascript Library which helps you keep your web application more organized by following MVP(Model View Presenter) approach and it is capable of communicating with the server in RESTful fashion .

First Lets lets see how to send GET request to the server using Backbone.JS and handling it at the backend using NODE.JS webserver which is built using the express framework . Basics of using express framework is also discussed in the last post .

Here is the link for the code from my github.com repo

Here is the Front end code using Backbone.JS to send GET request to the server

<!doctype html>
<html lang="en">
		<title>Backbone App</title>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<script type="text/javascript" src="http://underscorejs.org/underscore-min.js"></script>
		<!--  Underscore.JS is the dependency library for Backbone.JS-->
		<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
		<!-- Jquery is used for DOM manipulation-->
		<script type="text/javascript" src="http://backbonejs.org/backbone-min.js"></script>
		<!--Fieldset helps logically grouping the HTML elements  -->	
			<legend>Post Data To Node.JS Server</legend>
			<!-- Input Field to Enter the data to be sent to the server
				Backbone.JS code is written to send POST request to the server 
				on clicking the button -->
			<input type="text" id="course_type" placeholder="Enter the Course Name" required />
			<input type="button" id="post_data" value="Send data to the Server" /> 
	    	<legend>Get Data From Node.JS Server</legend>
	    	<input type="button" id="get_data" value="Get Data From Server">
	    	<!--Backbone.JS code is written to send GET request to the server on clicking the button -->
		<div id="data"></div>
		<!-- Div element where data from the server is placed-->
	<!-- Backbone.JS code starts here -->
	<script >
			Courses = Backbone.Collection.extend({
				console.log('Post Clicked');
				console.log('Get Clicked');
			function get_data_from_server(){
				var courses = new Courses();
				 		data = data_array.models[0].attributes;
				 		data = JSON.stringify(data);
				 		var data = "<p>" + data + "</p>" ; 
			function post_data_to_the_server(){
				var courses = new Courses();
				courses.fetch({data:{course_name:$('#course_type').val()},type:'POST' });



 All the functions which start with ‘$’ are derived from JQuery . Plain Javascript can be used instead of JQuery ,its just that coding becomes easier on using Jquery . Backbone Collection is an entity to hold a collection of data .The ‘url’ in the backbone.collection.extend() specifies the URL to which the request to be sent. By using Jquery’s $(‘#button_id’).click() callback functions are associated to the button , which gets executed on click of the button .Backbone.JS sends AJAx requests to the server.
function get_data_from_Server is used to to send GET request to the server Collection.fetch() sends a get request by default and fires the success function when it recieves a reply from the server with data attached in JSON format .Model is an individual entity and collection is a set of different instances of same model.The returned data contains an array of models and its attributes are picked and added onto the html of the page after which the data returned from the server is displayed on screen , Function post_data_to_the_server() is used to POST data to the server.The type:POST argument to the collection.fetch() in the below code makes sure that POST request is sent to the server with the data

Place the html inside a folder called public inside the root of the folder where server.js file is placed. Here is the code for Node.JS server to handle the Bakcbone request

var http = require('http');
var express = require('express');
/* Express Web Development Framework is used */
var app = express();

/* Specifying the public folder to place the static html and javascripts */

/* app.get listens to GET requests to the URL in the first argument 
   and callback function is executed in respose to it */
	console.log('Get Request obtained from Backbone.JS');
	data = {
		author:"Karthic Rao",
		backend:"NODE.JS and Express"
	} /*data to be sent to the client */
	/* The response type should be a JSON */ 
    /*The Javascript Object is converted to JSON and sent
     back to the browser as response*/
/*app.get listens to GET requests to the URL in the first argument 
   and callback function is executed in respose to it*/
	console.log('Post Request Accepted' );


Intructions to the run the application

1.Install the server’s dependency module[express in this case]

npm install express 

2.Save the server code as server.js and place the html inside the public folder as course.html

3.Run the application

node server 

4.Go to browser and visit 

Here is the snapshot of the application from browser window


I hope that this blog helped you guys understand the basics building a web application with node in the backend and Backbone in the front end , see you guys soon with another exciting post …..Till then Happy Coding 😀

Client-Server communication using Websockets and Node.JS[express,socket.io]


Hello ppl …………. !!! Its been a long long time since the last blog ….Well , be ready for raining techie-geeky Blogs 😀

What are the various ways you guys can think of using which data can be sent to the server from the front end …hmm,,,,, By Posting data to the Server ?????? Yes , data can be sent to the server by posting the required data from HTML forms . hmm,,,,,,Using AJAX ????Yes , AJAX is a very popular implementation using which browsers can interact with the server .But the question now would be “Dude the title of the post  suggests that Web-sockets too are used to interact and send data to the server ,  Then what the hell is a Web-socket 😯 , How different is it from other means by which data is sent to the server  😕 “

Now  you know that web-sockets are one of the means by which the front end JavaScript can interact and send data to the server , But here are the reasons why it is very different from other implementations which are used to achieve similar objective.Ever since the onset of web applications, developers have worked towards different ways of getting duplex communication between the server and the browser. Be it using Java, Flash, Comet, or many other workarounds, all aim to do the same. But for the first time, there is a specification to build a full-duplex communication system by using HTML5 WebSockets. WebSocket is a revolutionary, new communication feature in the HTML5 specification that defines a full-duplex communication channel operating over the Web through a single socket.It is not, and will never be, available on older browsers that are still in use. Socket.io is an abstraction layer for WebSockets,with Flash, XHR, JSONP, and HTMLFile fallbacks. Socket.io provides an easy server and client library for making real-time, streaming updates between a web server and a browser client.
The Wiki page “Unlike HTTP, WebSocket provides for full-duplex communication. Additionally, Websocket enables streams of messages on top of TCP. TCP alone deals with streams of bytes with no inherent concept of a message. Before WebSocket, port 80 full-duplex communication was attainable using Comet Channles; however, Comet implementation is nontrivial, and due to the TCP handshake and HTTP header overhead, it is inefficient for small messages.

Summing everything up , the advantage of websockets are listed below ,

  • The WebSocket protocol makes possible more interaction between a browser and a web site, facilitating live content without page refresh
  • Websockets are amazingly fast compared any other alternative implementations , so it can be used for creating Real-Time web applications (Games , Live News feed)
  • Websockets are Standardized being part of HTML5
  • Support across all major browsers
  • Ease of use

Ahhhhh , i believe all of you had enough going through the details of webSockets 🙄 😀 Lets start with how to make use of WebSockets features using Node.JS server in the backend . This is not an introductory tutorial on Node.JS ( Here is an introductory tutorial on writing WebServers using Node.JS ) .

Here are The NodeJs modules which are used in coding the backend .

  • Express – It is a Web Development  Framework for Node.JS ExpressJS
  • Socket.IO – Socket.io is a node module available through the npm,It has two parts: a client-side library that runs in the browser, and a server-side library for Node.JS. Both components have a nearly identical API. Like node.js, it is event-driven.(socket.io).The Client side JavaScript to be included will be generated dynamically by this module.

       Installing the dependencies

npm install express
npm install socket.io

The Server

var express = require('express');
var http = require('http');
var io = require('socket.io');

var app = express();
//Specifying the public folder of the server to make the html accesible using the static middleware

var server =http.createServer(app).listen(8124);
//Server listens on the port 8124
io = io.listen(server); 
/*initializing the websockets communication , server instance has to be sent as the argument */

	/*Associating the callback function to be executed when client visits the page and 
	  websocket connection is made */
	  var message_to_client = {
	  	data:"Connection with the server established"
	  /*sending data to the client , this triggers a message event at the client side */
	console.log('Socket.io Connection with the client established');
		/*This event is triggered at the server side when client sends the data using socket.send() method */
		data = JSON.parse(data);

		/*Printing the data */
		var ack_to_client = {
	  	data:"Server Received the message"
		/*Sending the Acknowledgement back to the client , this will trigger "message" event on the clients side*/


Save the code in a file called server.js , run it using node executable (node.js should be installed on the system) ” node server.js ”

Create a folder by name public and place the html file inside it .

Here is socket.html file which handles the client side connection (save it inside a folder named public within the root directory of the server file)

<!DOCTYPE html>
<html lang="en">
		<title>webSockets and Socket.IO</title>
		<script type="text/javascript" src="/socket.io/socket.io.js"></script> 
		<!--The above library(/socket.io/socket.io.js) will be generated by socket.io module of server -->
		<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script> 
			<input type="text" id="message" /> <!--text form to send data to the server-->
			<input id="submit" type="button" value="Send data to Server">
			<div id="content"></div> <!--This is where the data from the server is added-->


		<script type="text/javascript">
			var socket = io.connect("/"); 
			/*Initializing the connection with the server via websockets */
					When server sends data to the client it will trigger "message" event on the client side , by 
					using socket.on("message") , one cna listen for the ,message event and associate a callback to 
					be executed . The Callback function gets the dat sent from the server 
				console.log("Message from the server arrived")
				message = JSON.parse(message);
				console.log(message); /*converting the data into JS object */
				$('#content').append('<div >'+message.data+'</div>'); /*appending the data on the page using Jquery */
				$('#submit').click(function(){ /*listening to the button click using Jquery listener*/
					var data = { /*creating a Js ojbect to be sent to the server*/ 
						message:$('#message').val(), /*getting the text input data  	*/
					/*Data can be sent to server very easily by using socket.send() method 
					The data has to be changed to a JSON before sending
                                          it (JSON.stringify() does this job )*/
					/* This triggers a message event on the server side 
					and the event handler obtains the data sent */ 

					//Emptying the text box value using jquery 



Go to the browser and visit the URL

The comments inside the code explains it

Here is the screenshot of the application


Hope that this blog was very interesting and helped you to understand how to use websockets to communicate with the Node.JS server …..Will come back soon with lot more exciting posts , till then Happy Coding 😀





Guide on writing socket programs using NODEJS : A simple Server using NODE

Hi folks !!!!! Here goes one more simple tutorial on using NODEJS.I’ve been fascinated by the ease with which one could create TCP and HTTP servers using NODEJS.This post is special since its my 100th blog.Its been a great journey starting from september 2011 , i thank Vignesh Prabhu from FSMK for pursuing me very much to start writing a blog for which im very glad today on the occasion of writing my 100th blog post

we shall start by writing the simplest socket program , A NODEJS program which just opens up and listens on port 9225

var net = require('net'); //Load the module , net module provides all functionalities to write sockets in NODEJS

var server = net.createServer( function(conn) {

       //This is the event handler function which illustrates the action once the connection is established with client , nw the function is empty
}).listen(9225); //listens to port 9225

You can see use the command `netstat -ant’ and see the port 9225 listening

This is how the structure of a server program using NODEJS looks like

var net=require('net');
var server=net.createServer(function(conn){ 
	////write code here on want action you want to achieve once the connection is established with the client 
	conn.on('data',function(data) {
         //write code here on want action you want to achieve once the connection is established and data flows in from client 
	//write code here on want action you want to achieve once the client closes his end of the connection

} ).listen(9225); //use any valid port number for the server to listen

I believe the last part clearly illustrated the structure of a TCP server using NODEJS , now we’ll take a look a look at a sample code making use of the same structure illustrated above

var net = require('net');
var server = net.createServer( function() {
	console.log('Connection Established'); 
	conn.on('data',function(data) {
		console.log(data + 'from' + conn.remoteAddress +  ' ' +  conn.remotePort );
		conn.write('Thank you , data successfully accepted'); //writing bck to the client 
	conn.on('close' , function() ( 
		console.log('Client Closed the connection');
	console.log('Listening to port 9225');