Encrypt and Decrypt Data in Node.js

Encrypt and Decrypt Data in Node.js

Node.js provides 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 new directory anywhere in your system and create new project using the following command:

npm init -y

If you have installed Node.js by manual build then there is a chance that crypto library is not shipped with it. You can run this command to install 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")
console.log(hw)
console.log(decrypt(hw))

Here is the output:

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"))
console.log(hw)
console.log(decrypt(hw))

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

Conclusion

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.

This article was published on Codeforgeek.


To view or add a comment, sign in

More articles by Shahid Shaikh

  • Redistill - High Performance Redis Compatible Key Value Database

    Redis has always been one of my go-to KV databases. I strongly believe in — and advocate for — a memory-first…

  • 10 ChatGPT Prompts to Boost Developer Productivity

    As developers and engineers, we constantly seek ways to streamline our workflows, increase productivity, and solve…

    1 Comment
  • Building Live Face Detector using Node.js and OpenCV

    Computer Vision in nutshell is defined as “making computers see and understand things the way we humans do”. This seems…

    1 Comment
  • Top 5 Best Node Frameworks

    Node.js is an open source, cross platform JavaScript runtime engine to develop server side applications.

    1 Comment
  • Kafka Setup for Production

    Apache Kafka is an open source distributed streaming platform developed by LinkedIn and managed by the Apache software…

  • Automate your workflow with Github Actions

    Github announced a new feature around a month ago called Action which would be workflow system inbuilt inside Github…

  • Fixing Time to First Byte Issue in WordPress

    Do you use WordPress? Do you use Nginx as the Web Server? Do you use SSL as well, because hey it’s ranking factor? And…

Explore content categories