Encrypt and Decrypt Data in Node.js

Node.js provides a built-in library called ‘crypto’ which you can use to perform cryptographic operations on data. You can do cryptographic operations on strings, buffer, and streams.

In this article, we will go through some examples of how you can do these operations in your project.

You can use multiple crypto algorithms. Check out the official Node.js docs here.

For the sake of examples, I am going to use AES (Advanced Encryption System) algorithm.

Create a new node.js project

Create a new directory anywhere in your system and create a new project using the following command:

npm init -y

If you have installed Node.js by manual build then there is a chance that the crypto library 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.

Let’s move ahead.

Encrypt and decrypt data (Strings, numbers etc)

// Nodejs encryption with CTR
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('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') };

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();

var hw = encrypt("Some serious stuff")

Here is the output:

Encrypt and decrypt Nodejs

Encrypt and decrypt buffer

You can also encrypt and decrypt the buffers. Just pass the buffer in place of the string when you call the function and it should work.

Like this.

var hw = encrypt(Buffer.from("Some serious stuff","utf-8"))

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


I hope the samples help you to get started with nodejs encryption.

If you have any questions or doubts, tweet me @codeforgeek or just leave a comment. I’ll reply as soon as possible.

4 thoughts on “Encrypt and Decrypt Data in Node.js”

  1. I’m not a programmer but I tried to set up a encryption using postman and webtask.io

    1. Post text and get back an encrypted message
    2. Post encrypted text and get back decoded

    Not sure if this script would need modifications for that?

    1. Hey Mark. I actually have programmed a few node apis and yes it can be done with modification. I believe you should include express so as to create a RESTFul API. Once you’ve sorted out the routing and all, using Postman should be easy.

  2. Thanks for your demonstration. I have a question.

    Why did you use `Buffer.from(key)` instead of just `key` and use `Buffer.concat([encrypted, cipher.final()]);` with `encrypted.toString(‘hex’)` instead of just `encrypted += cipher.final(‘hex’)`? As I have tried, they produce the same result.

  3. Is the initialisation vector in this static? If so how would this be secure in practice? As what I’m seeing in this is that the IV needs to be supplied along with the encrypted data in order for you to be able to decrypt it assuming the encryption and decryption is done in separate places.

    In my use case, i can only supply a sinlge string, not an object, so i can’t feasibly supply both. Or is simply concatenating them (with a known IV length) fine?

Comments are closed.