How to Encrypt and Decrypt data in Node.js using AES-256 | Anjal Bam

Encrypt and decrypt like a pro.

·

4 min read

Encryption is a privacy tool/technique when we are sending or storing sensitive, confidential, or personal information across the internet.

Encryption changes the plain readable text to a secret type of code that hackers, criminals, or other nefarious people on the internet cannot read before it reaches the intended recipients. When the message does get to its recipients, they use the decryption key to convert the unreadable text into plain readable text.

How does encryption work?

Encryption takes plain text, like a text message, username, or email, and scrambles it into an unreadable format called the "cipher text". This helps protect the privacy or confidentiality of digital data either stored or transferred via the internet.

When the intended recipient accesses the message, the recipient will have to use a "secret" encryption key which is used by the sender to encrypt the message and is translated back to its original form. This process of changing the cipher text back to the original message is called decryption.

There are various types of encryption methods such as RSA, Data Encryption Standard (DES), Triple DES (Runs DES three times? -Yes!), Advanced Encryption Standard (AES), etc.

What will we be doing today?

Today, we are going to learn how to encrypt and decrypt data in Node.js using the Advanced Encryption Standard (AES) algorithm.

Prerequisites: Node.js version min 12.xx, and some familiarity with JavaScript syntax.

Create a new project

Let's create our working directory.

$ mkdir cryptography

Switch to the working directory.

$ cd cryptography

Now initialize a new Node.js project with the following command.

$ npm init -y

The above command will generate a new package.json file in the root directory.

The crypto module is default shipped with the built-in Node.js binaries but if you have manually installed it, the crypto module can be installed with the following command:

$ npm install crypto --save

Encrypt and decrypt text

Create an index.js file in the root directory.

Let's start by importing our required module from Node.js

const crypto = require('node:crypto');

The crypto, a Node.js built-in module provides the necessary classes for us to use while encrypting and decrypting strings, numbers, buffers, streams, and more. This module provides a wrapper to cryptographic functionalities including wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign and verify functions.

Now define the algorithm and "secret" key to use:

const secretKey = 'aelwfhlaef';
const secretIV = 'aifjaoeifjo';
const encMethod = 'aes-256-cbc';

The variables above will be used throughout the program. The secretKey is used to create a secret hash to use as a key to encrypt. The secretIV will be used to create an IV for the encryption and the encMethod is the encryption we'll use to encrypt the data i.e. aes-256-cbc.

Let's generate secret keys to use in our encryption:

const key = crypto.createHash('sha512').update(secretKey).digest('hex').substring(0,32)
const encIv = crypto.createHash('sha512').update(secretIV).digest('hex').substring(0,16)

Since now we have our keys generated, lets define the encrypt function that takes 'text' as an argument and returns the encrypted cipher text.

function encryptData (data) {
    const cipher = crypto.createCipheriv(encMethod, key, encIv)
    const encrypted = cipher.update(data, 'utf8', 'hex') + cipher.final('hex')
    return Buffer.from(encrypted).toString('base64')
}

In the above function encryptData we first create a Cipher instance with the given algorithm aes-256-cbc, secretKey and encIV. Which is then updated with our data with the update() method and once the final() method is called the cipher object now cannot be used to update the data. The result is first converted into a buffer with Buffer.from() and converted to a string with toString() method.

Now since the given text is encrypted, we create a function to decrypt the encrypted data.

function decryptData(encryptedData) {
    const buff = Buffer.from(encryptedData, 'base64')
    encryptedData = buff.toString('utf-8')
    const decipher = crypto.createDecipheriv(encryptionMethod, key, encIv)
    return decipher.update(encryptedData, 'hex', 'utf8') + decipher.final('utf8')
}

The above functions are similar, but in this case we generate a Decipher instance with the algorithm, key, and IV, update the data with update() method and finish decrypting with the final() method, and finally return the decrypted data.

Conclusion

In this article, we had a thorough look at how to perform cryptographic operations to encrypt and decrypt text data by using the Node.js built-in crypto module, which is very important to store or send sensitive information in the database or to the recipients over the internet respectively.

✌️Like this article? Connect to me on LinkedIn and GitHub.