In this article we will learn about how encryption and decryption is performed using nodejs.
Data that can be read and understood easily is known as Plain text. The problem with plain text is
that everyone can read it.
But sometimes we don't want everyone to have the access to read the data i.e. the confidentiality of the data
need to be maintained.
As we all must have heard about the CIA Information security triads as mentioned in the image below :
encryption deals with providing confidentiality to the data.
In encryption , Plain text is translated to an unintelligible text which we can read but can not understand due
to which the confidentiality of the data is protected. This unintelligible text is known as Cipher text.
hence ,
So encryption is done with the help of key . The key can be anything (number, digit , phrase , word, etc). Lets see an example
of encryption using a key (sometimes also referred as salt) using nodejs as mentioned in the image.
The code snippet is given below for encryption as well as decryption :
var crypto = require('crypto'),algorithm = 'aes-256-ctr',password = 'RJ23edrf';
//Here "aes-256-cbc" is the advance encryption standard we are using for encryption.
//Text is the Confidential data which we need to encrypt using 'password'(Key).
function encrypt(text){
var cipher = crypto.createCipher(algorithm,password)
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}
Decryption is the process of rendering the data , so that it can be changed into a human or machine readable and
understandable form.It takes the cipher text as input and converts it into the plain text with the help of KEY
and AES algorithms.
Therefore ,
Decryption is used to get the original readable data from the cipher text with the help of the "key" which was
used for encryption. If you are not having the right key then you will not be able to retrieve the original
text.The Snippets for decryption is given below :
// Decryption
var crypto = require('crypto');
algorithm = 'aes-256-ctr';
password = 'RJ23edrf';
//Here "aes-256-cbc" is the advance encyption standard we used for encrytion.
//Text is the Cipher which we need to decrypt using 'password'(Key).
function decrypt(text){
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
var text = "Nodejsera for all web development languages";
var e = encrypt(text);
console.log(e);
var d = decrypt(e);
console.log(d);