How to encrypt and decrypt Data using node.js

Encryption and Decryption are basically used for security purposes. We convert our actual data in some other form using some algorithms sha, RSA, etc during encryption. Vice versa we convert our encrypted data into actual forum during decryption.

In Node.js for Encryption and Decryption, we use crypto
package.

During Encryption and, Decryption we use security keys to make our encryption more strong.

For Encryption and, Decryption, we also used term encoding and decoding. During encryption, we encode our data and during decryption, we decode our data. 

Now we will write code for encrypting our data then after we will write code for decrypting our data.

But before that at first, we will declare our security keys that we are using for encryption and decryption.


// Declare package
var crypto = require('crypto');
// Declareing secret_key
let secret_key = 'encrypton_decryption';
// Declare secret_iv
let secret_iv = 'encrypton_decryption_iv';
// Declare encryption method
let encrypt_method = "AES-256-CBC";

Then after we will write code for encrypting our data as shown below.


const encryptData = async function (data) {
  let key = crypto.createHash('sha256').update(secret_key).digest('hex').substr(0, 32);
  let iv = crypto.createHash('sha256').update(secret_iv).digest('hex').substr(0, 16);
  let cipher = crypto.createCipheriv(encrypt_method, key, iv);
  let encrypted = cipher.update(data, 'utf8', 'base64');
  encrypted += cipher.final('base64');
  return Buffer.from(Buffer.from(encrypted).toString('utf8')).toString('base64');
}

For calling this function we write these lines of code


let hw = encryptData("hello");
console.log(hw);

OutPut:
encrypt data
Now for decryption of our data, we will write these lines of code


const decryptData = async function (data) {
  let key = crypto.createHash('sha256', secret_key).update(secret_key).digest('hex').substr(0, 32);
  let iv = crypto.createHash('sha256', secret_key).update(secret_iv).digest('hex').substr(0, 16);
  var decipher = crypto.createDecipheriv(encrypt_method, key, iv);
  var dec = decipher.update(Buffer.from(data, 'base64').toString('ascii'), 'base64', 'utf8');
  dec += decipher.final('utf8');
  return Buffer.from(dec).toString('utf8');
}

And during calling decryptData function we will pass encrypted data that has been obtained from encryptData function as shown below


let decryphw = decryptData('SEJFL0VVYy83SGcwc1prZFZST3A2Zz09');
console.log(decryphw);

OutPut:

Leave a Reply

Your email address will not be published. Required fields are marked *