Encrypt and Decrypt Data in Node.js Using Crypto: A Step-by-Step Guide

In Node.js we perform a lot of operations on data, which involves transferring data simultaneously from server to client and from client to server. There may be a possibility of a data breach while transferring data. To avoid this we can encrypt the data and then decrypt it later to get the same output ensuring data integrity.

In this article, we will learn about the Node.js Crypto Module used to encrypt and decrypt data. We will learn how to do encryption and decryption using cryptography techniques for both string and buffer data. Let’s get started.

Node.js Crypto Module

Node.js includes a built-in module called ‘crypto’ which you can use to perform cryptographic operations on data. You can do cryptographic operations on strings, buffers, and streams. This includes encrypting, decrypting, hashing, etc. You can also use various encryption algorithms when using the ‘crypto’ module. Click here to get the list. For this article, we will be using AES (Advanced Encryption System) algorithm.

Install Crypto Module

If you have installed Node.js by manual build then there is a chance that the ‘crypto’ is not shipped with it. You can run this command to install the ‘crypto’ dependency.

npm install crypto --save

You don’t need to do that if you have installed it using pre-built packages.

Encrypt and Decrypt Data in Node.js

Let’s now write code for encrypting and decrypting data. Let’s start with a basic setup.

Step 1: Create a new folder & open it on the code editor.

Step 2: Create a file ‘aap.js’ inside that folder.

Step 3: Open the terminal & type the below command. This initializes the Node Packages Manager, by which we can install any Node.js framework.

npm init -y

Step 4: Inside the terminal, type the below command to install ‘crypto’ as a dependency in the project folder.

npm install crypto --save

Step 5: Open the ‘app.js’ file and write the following code for data encryption and decryption.

app.js

const crypto = require('crypto'); // Import the crypto module
const algorithm = 'aes-256-cbc'; // Use AES 256-bit encryption
const key = crypto.randomBytes(32); // Generate a random 32-byte key
const iv = crypto.randomBytes(16); // Generate a random 16-byte IV

function encrypt(data) { // Function to encrypt data
    let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
    let encrypted = cipher.update(data);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return {
        iv: iv.toString('hex'),
        encryptedData: encrypted.toString('hex')
    };
}

function decrypt(data) { // Function to decrypt data
    let iv = Buffer.from(data.iv, 'hex');
    let encryptedText = Buffer.from(data.encryptedData, 'hex');
    let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
}

var data = "Username & Password" // Data to be encrypted

var encrypted = encrypt(data); // Encrypt the data
console.log("Encrypt Data: ", encrypted)

var decrypted = decrypt(encrypted); // Decrypt the data
console.log("Decrypt Data: ", decrypted)

Explanation:

  • First, we have imported the ‘crypto’ module using require().
  • Then we have defined an encryption algorithm to use for encryption. We have used AES (Advanced Encryption Standard) with a 256-bit key length in CBC (Cipher Block Chaining) mode.
  • Then we used the randomBytes() function to generate a random 32-byte secret key.
  • Then we used the same method to generate a random 16-byte IV ( Initialization Vector).
  • Then we have defined a function ‘encrypt’ that takes raw data, encodes it and returns the encrypted one using the crypto module.
  • Similarly, we have defined another function ‘decrypt’ to decrypt the encrypted data.
  • At last, we passed the plaintext having some random data to encrypt() functions and then converted ciphertext to decrypt() to see the results.

Run the Application

The code is written in a single file ‘app.js’ that runs on executing the below command in the terminal.

node app.js

Output:

Encrypt Decrpyt Data

Encrypt and Decrypt Buffer in Node.js

In the above section, we have done encryption and decryption of a string. To encrypt and decrypt buffers, you can simply pass the buffer in place of the string during the function call and it will encrypt and decrypt it accordingly.

app.js

const crypto = require('crypto'); // Import the crypto module
const algorithm = 'aes-256-cbc'; // Use AES 256-bit encryption
const key = crypto.randomBytes(32); // Generate a random 32-byte key
const iv = crypto.randomBytes(16); // Generate a random 16-byte IV

function encrypt(data) { // Function to encrypt data
    let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
    let encrypted = cipher.update(data);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return {
        iv: iv.toString('hex'),
        encryptedData: encrypted.toString('hex')
    };
}

function decrypt(data) { // Function to decrypt data
    let iv = Buffer.from(data.iv, 'hex');
    let encryptedText = Buffer.from(data.encryptedData, 'hex');
    let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
}

var data = "Username & Password" // Data to be encrypted

var buffer = Buffer.from(data); // Convert the data to a buffer

var encrypted = encrypt(buffer); // Encrypt the data

console.log(encrypted);

var decrypted = decrypt(encrypted); // Decrypt the data
console.log(decrypted);

Output:

Encrypt Decrpyt Buffer

You can also pipe the streams into the encrypt() function to have secure encrypted data passing through the streams.

Conclusion

In this article, we have discovered the crypto module provides different functions for performing encryption and decryption in Node.js applications. This is done in order to secure data, to protect sensitive data from malicious parties. We can use this module to convert plain text into unreadable text and vice versa. We can either encrypt & decrypt both plain text or buffer data. Hope you have enjoyed reading the content. Check out more interesting articles on NodeJS below.

Read More:

Reference 

How to encrypt data that needs to be decrypted in node.js?

Aditya Gupta
Aditya Gupta
Articles: 133