Encrypt and Decrypt Data in NodeJS


NodeJS provides inbuilt library crypto to encrypt and decrypt data in NodeJS. We can use this library to encrypt data of any type. You can do the cryptographic operations on a string, buffer, and even a stream of data. The crypto also holds multiple crypto algorithms for encryption. Please check the official resources for the same. In this article, we will use the most popular AES (Advanced Encryption Standard) for encryption.

Configuring 'crypto' dependency

  • In your project, check if NodeJS is initialized or not. If not, use the following command to initialize NodeJS.

>> npm init -y
  • The 'crypto' library is automatically added while installing the node manually. If not, you can use the following command to install crypto.

>> npm install crypto –save

Example

Encrypting and Decrypting Data

//Checking the crypto module
const crypto = require('crypto');
const algorithm = 'aes-256-cbc'; //Using AES encryption
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

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

// Decrypting text
function decrypt(text) {
   let iv = Buffer.from(text.iv, 'hex');
   let encryptedText = Buffer.from(text.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();
}

// Text send to encrypt function
var hw = encrypt("Welcome to Tutorials Point...")
console.log(hw)
console.log(decrypt(hw))

Output

C:\Users\mysql-test>> node encrypt.js
{ iv: '61add9b0068d5d85e940ff3bba0a00e6', encryptedData:
'787ff81611b84c9ab2a55aa45e3c1d3e824e3ff583b0cb75c20b8947a4130d16' }
//Encrypted text
Welcome to Tutorials Point... //Decrypted text

Updated on: 12-Sep-2023

34K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements