Member-only story
Encrypting data is an essential security aspect, especially when working with sensitive data. Node.js provides a built-in crypto module that can be used for encryption purposes. In this tutorial, we will explore how to encrypt data using Node.js.
Not a Medium member? Read this article here
Step 1: Import the crypto module To use the crypto module, we need to require it in our code as follows:
const crypto = require('crypto');
Step 2: Create a cipher object To encrypt data, we must create a cipher object. The cipher object takes an algorithm and a key as arguments.
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algorithm, key, iv);
Here, we are using the AES-256-CBC algorithm to encrypt our data. We generate a random key and IV (initialization vector) using the crypto.randomBytes() method.
Step 3: Encrypt the data Now that we have a cipher object, we can use it to encrypt our data. We can do this by calling the update() and final() methods on the cipher object.
let encrypted = cipher.update('Hello World', 'utf8', 'hex');
encrypted += cipher.final('hex');