NodeJS Crypto Module – Encrypt and Decrypt Data

NodeJS Crypto is a built-in module used to perform several types of encryption and decryption.

NodeJS is used to create many applications, and some contain confidential information that should be highly secure. To secure that information, it is required to encrypt them so that a hacker or outsider can not be able to understand it.

Encrypt means converting the information into a form that is not understandable to others. The processing of converting plain text into encrypted format is called encryption.

Let’s understand the uses of encryption with an example. Suppose we are creating a website where we ask for a username and password and we store that data in a database to authenticate the user when they come again. But the database used is stored in a third-party cloud and it can be hacked and the user’s password and username can be leaked.

This is called a data breach.

To ensure that even after the data breach:

  • the password is safe, we have to encrypt them into a form that hackers can not understand.
  • When a user comes and login we just encrypt the entered password with the same algorithm.
  • Then we match it with the encrypted one in our database.
  • If it is the same, then authenticate the users.

Let’s understand how we can do so using the NodeJS crypto module.

Node.js Crypto Module

Node.js Crypto Module can be imported using the below statement.

Syntax

const crypto = require('crypto');

Data Encryption Using Node.js Crypto Module

The Node.js Crypto Module provides the createCiphervie method for converting plain text into cipher text. This method takes three arguments to create a cipher object which is then used to encrypt the plain text.

List of arguments used by the createCiphervie method.

  1. Algorithm – There are various algorithms that can to used to encrypt passwords, and for again decrypting the password it is mandatory to use the same algorithm.
  2. Key – A key is a unique value that must be the same for encryption and decryption, this ensures that either hacker knows the algorithm they are not able to decrypt the encrypted text because the key is unknown to them.
  3. IV – The last argument is an IV, initialization vector, used with the key to performing encryption and description.

Syntax:

crypto.createCipheriv(algorithm, key, iv);

The procedure of encryption using Node.js Crypto Module

  1. We will start with importing the crypto module.
  2. Initiate a constant containing the algorithm we want to use.
  3. Generate random key and IV.
  4. Create a function with takes text as an argument.
  5. Inside the function use the createCiphervie method and pass the algorithm, key, and IV, then set it to a variable cipher.
  6. Use the cipher variable to update the text passed as an argument, this will convert the plain text into encrypted text.
  7. Then concatenate the encrypted text and use cipher.final() method.
  8. Return an object containing the IV and encrypted text.

Example:

Let’s encrypt a string “Hello World!” using the above procedure. 

const crypto = require('crypto');

const algorithm = 'aes-256-cbc';

const key = crypto.randomBytes(32);

const iv = crypto.randomBytes(16);

function encrypt(text) {
    let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return { iv: iv.toString('hex'),
    encryptedData: encrypted.toString('hex') };
}

var encrypted = encrypt("Hello World!");
console.log("Encrypted Text: " + encrypted.encryptedData);

Output:

Encrypted Text: bd694d9bcf99f1268c18231a9d856a38

Decryption using Node.js Crypto Module

For decryption, the Node.js Crypto module provides a method createDeciphervie which works exactly the same as createCiphervie. 

Syntax:

crypto.createDecipheriv(algorithm, key, iv);

The procedure of decryption using Node.js Crypto Module

  1. Create a function with takes encrypted data as an argument.
  2. Fetch the IV and encrypted text from the data pass as an argument.
  3. Use the createDeciphervie method and pass the algorithm, key, and IV then set the function to a variable decipher.
  4. Use the decipher variable to update the decrypted text.
  5. Then concatenate the decrypted text and use decipher.final() method.
  6. Return the plain text.

Example:

We use the data gets as an output of encrypt method and then decrypt it to get the plain text. For getting the exact same plain text, the algorithm, key, and IV must be the same.

const crypto = require('crypto');

const algorithm = 'aes-256-cbc';

const key = crypto.randomBytes(32);

const iv = crypto.randomBytes(16);

function encrypt(text) {
    let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return { iv: iv.toString('hex'),
    encryptedData: encrypted.toString('hex') };
}

var encrypted = encrypt("Hello World!");

function decrypt(text) {
    let iv = Buffer.from(text.iv, 'hex');
    let encryptedText = Buffer.from(text.encryptedData, 'hex');

    let decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), iv);

    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);

    return decrypted.toString();
}

const decrypted = decrypt(encrypted)
console.log("Decrypted Text: " + decrypted);    

Output:

Decrypted Text: Hello World!

Summary

Node.js Crypto is used for encryption and description to ensure the confidentiality of a message. It can be used to encrypt the password and important data. It can also be used when creating a chat application to encrypt the message before sending it so that it can’t be read by a hacker. Hope this article will help you to understand the processor of encryption and decryption using the Node.js Crypto module. 

Reference

https://nodejs.org/api/crypto.html#crypto

Aditya Gupta
Aditya Gupta
Articles: 133