Encrypt and Decrypt data in Node.js using Crypto module

Today, I am going to let you know, how to encrypt data and then decrypt it back to get the original data in Node.js.

I hope you have some idea of encryption and decryption. In brief, encryption is the process of hiding the original data with encrypted data. On the other hand, decryption is the process of getting back the encrypted data to its original form.

The purpose of encryption and decryption of data is to provide security. With this process, confidential data protected and only accessible to the receiver.

In Node.js, we can encrypt data and also decrypt data to get back the original data. Node.js has a module which is the Crypto module. Using the Node.js Crypto module, we can encrypt and decrypt data or string.

Encrypt data

Below is the Node.js code to encrypt data:

var crypt = require('crypto');

var key = crypt.createCipher('aes-128-cbc', 'password_key');
var encrypted_str = key.update('Welcome to CodeSpeedy', 'utf8', 'hex')
encrypted_str += key.final('hex');

console.log(encrypted_str); //ed42eea62e37f699cd7c5b936597f3059023e16e2dab52cfeacfb9b690c21937

In the above Node.js JavaScript code, we have created the createCipher() method from the Crypto module to create a cipher object. We have set the algorithm and also set a password key that will be used to encrypt our string.

The data that we want to encrypt is a string which is “Welcome to CodeSpeedy”. Now if we run the above code, we will able to see the encrypted data or string on the console.

Decrypt the encrypted data

Now it’s time to see how we can decrypt the encrypted data to get its original form. Below is the Node.js JavaScript code to decrypt the encrypted data back:

var crypt = require('crypto');
var key = crypt.createDecipher('aes-128-cbc', 'password_key');
var decrypted_str = key.update(encrypted_str, 'hex', 'utf8')
decrypted_str += key.final('utf8');
console.log(decrypted_str); // Welcome to CodeSpeedy

In the above code, we are able to get our original data back after we decrypt our encrypted data.

In our code, we have used the createDecipher() method. It returns a decipher object. Here we have passed the password key which we had passed to encrypt the data. The createDecipher() is just the opposite of createCipher() method.

Now if we run the code, we can see the original string “Welcome to CodeSpeedy” in the console which proves that we are able to get our decrypted string.

So in this tutorial, we have successfully able to encrypt and decrypt data in Node.js using the Crypto module.

Also, read:


Leave a Reply

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