Data Encryption and Decryption in Node.js using Crypto (2022)

Web applications have access to large amounts of data that belongs to people, organizations, and governments. The more the data is accessed, the higher the threat to data security. In the software development industry, developers use cryptography and encryption techniques to protect sensitive data from malicious parties.

Cryptography is used to secure data stored in a database or transferred over a software development industry network. When handling, moving, and storing data, you must do it safely and securely.

Thus as a node.js developer, you should understand how to encrypt and decrypt data to secure data processed by your system. Node.js has a built-in library called crypto for data encryption and decryption.

Encryption and decryption aim to enhance safety. This article will help you learn how to use the Node.js crypto module to encrypt and decrypt data in your applications. Also, it will summarize cryptography in node.js.

Table of contents

  • Cryptography in node.js
  • Node.js crypto module
  • How to encrypt data in Node.js
  • How to decrypt data in Node.js

Prerequisites

A comprehensive understanding of cryptography and node.js is required before reading this article. Also, you should have:

Cryptography in node.js

Cryptography is crucial for software development. Data must be protected. Cryptography is a study of techniques on how to keep the data secure. It converts the data into a secret by converting plaintext into unreadable text and vice versa. Hence only the sender and the receiver of that data can understand its content.

The three main components of a cryptosystem include plaintext, ciphertext, and algorithm. To make information a secret, we use a cipher and an algorithm that turns plaintext into ciphertext. Converting data into unreadable text is called encryption, and reversing it back to plaintext is decryption.

Cryptographic algorithms use a key to convert plaintext to ciphertext. Converting ciphertext back to plaintext is possible only if you have the right key with you.

(Video) How to Encrypt and Decrypt string in Node JS using Crypto Module using key | Cryptography

You use symmetric encryption if you encrypt and decrypt data using the same key. Asymmetric encryption is used if different keys are used for encryption and decryption.

To protect data in Node.js applications, you have to store the hashed passwords in the database. This way, you cannot convert data into plaintext after it is hashed. It has to be verified.

If malicious attackers gain access to the database, they won’t read the data since it’s encrypted. Moreover, they do not have the key to help them do so.

Node.js crypto module

The Node.js crypto module provides cryptographic operations to help you secure your Node.js application. It supports hashes, HMAC for authentication, ciphers, deciphers, and more.

As stated earlier, crypto is a built-in library in Node.js. Thus it doesn’t require installation and configuration before using it in your Node.js applications. The crypto module handles an algorithm that performs encryption and decryption of data.

The crypto module authorizes you to hash plain texts before storing data in a database. Hashed data can not be decrypted with a specific key, like encrypted data. Instead, an HMAC is responsible for a Hash-based Message Authentication Code, which hashes keys and values to create a final hash.

You may want to encrypt and decrypt data for transmission purposes. This is where cipher and decipher functions come in. You encrypt data with a cipher and decrypt it with a decipher. Also, you may want to encrypt data before storing it in the database.

To verify encrypted or hashed passwords. It would be best to have a verify function. Let us explore data encryption and decryption and implement Node.js applications using crypto.

Getting started with a Node.js project

We’ll create a Node.js project to work with crypto. You’ll learn how to encrypt and decrypt data. To begin, execute this command:

npm init -y
(Video) Encryption and Decryption in Node.js

By default, the crypto module is an in-built Node.js library. But if Node.js is installed manually, crypto may not be delivered with it. To install, execute the following command:

npm install crypto --save

You do not need to execute the command if crypto is installed using pre-built packages.

How to encrypt data in Node.js

To get started, create the app.js file and define our encryption functions as shown below.

First, you will import the crypto module:

const crypto = require ("crypto");

While encrypting data, it’s vital to use an algorithm. In this project, we use aes-256-cbc.

The crypto.randomBytes() method is used to generate cryptographically built random data generated in the written code.

The initVector (initialization vector) is used here to hold 16 bytes of random data from the randomBytes() method, and Securitykey contains 32 bytes of random data.

// crypto moduleconst crypto = require("crypto");const algorithm = "aes-256-cbc"; // generate 16 bytes of random dataconst initVector = crypto.randomBytes(16);// protected dataconst message = "This is a secret message";// secret key generate 32 bytes of random dataconst Securitykey = crypto.randomBytes(32);
(Video) Encrypt and Decrypt String using Node JS and Mongo DB

To encrypt the data, the cipher function is used. Our project’s cipher function is made using createCipheriv(), the initialization vector from the crypto module.

Pass the first argument as the algorithm we are using, the second argument as the Securitykey, and initVector as the third argument.

To encrypt the message, use the update() method on the cipher. Pass the first argument as the message, the second argument as utf-8 (input encoding), and hex (output encoding) as the third argument.

// crypto moduleconst crypto = require("crypto");const algorithm = "aes-256-cbc"; // generate 16 bytes of random dataconst initVector = crypto.randomBytes(16);// protected dataconst message = "This is a secret message";// secret key generate 32 bytes of random dataconst Securitykey = crypto.randomBytes(32);// the cipher functionconst cipher = crypto.createCipheriv(algorithm, Securitykey, initVector);// encrypt the message// input encoding// output encodinglet encryptedData = cipher.update(message, "utf-8", "hex");

The code tells cipher to stop the encryption using the final() method. When the final() method is called, the cipher can’t be used once more to encrypt data.

The message is then encrypted, and malicious attackers can’t understand the encoded data. Below is an example of how to encrypt data:

// crypto moduleconst crypto = require("crypto");const algorithm = "aes-256-cbc"; // generate 16 bytes of random dataconst initVector = crypto.randomBytes(16);// protected dataconst message = "This is a secret message";// secret key generate 32 bytes of random dataconst Securitykey = crypto.randomBytes(32);// the cipher functionconst cipher = crypto.createCipheriv(algorithm, Securitykey, initVector);// encrypt the message// input encoding// output encodinglet encryptedData = cipher.update(message, "utf-8", "hex");encryptedData += cipher.final("hex");console.log("Encrypted message: " + encryptedData);

Here is the output:

Data Encryption and Decryption in Node.js using Crypto (1)

How to decrypt data in Node.js

Decrypting data follows a similar format to that of encrypting data. In our Node.js project, we will use the decipher function to decrypt data. Thus, our project encrypts and decrypts data.

(Video) Cryptography - Node.js Basics Part 8

Below is an example of how to decrypt data:

// the decipher functionconst decipher = crypto.createDecipheriv(algorithm, Securitykey, initVector);let decryptedData = decipher.update(encryptedData, "hex", "utf-8");decryptedData += decipher.final("utf8");console.log("Decrypted message: " + decryptedData);

Follow the below example to encrypt and decrypt data using crypto:

// crypto moduleconst crypto = require("crypto");const algorithm = "aes-256-cbc"; // generate 16 bytes of random dataconst initVector = crypto.randomBytes(16);// protected dataconst message = "This is a secret message";// secret key generate 32 bytes of random dataconst Securitykey = crypto.randomBytes(32);// the cipher functionconst cipher = crypto.createCipheriv(algorithm, Securitykey, initVector);// encrypt the message// input encoding// output encodinglet encryptedData = cipher.update(message, "utf-8", "hex");encryptedData += cipher.final("hex");console.log("Encrypted message: " + encryptedData);// the decipher functionconst decipher = crypto.createDecipheriv(algorithm, Securitykey, initVector);let decryptedData = decipher.update(encryptedData, "hex", "utf-8");decryptedData += decipher.final("utf8");console.log("Decrypted message: " + decryptedData);

Here is the output:

Data Encryption and Decryption in Node.js using Crypto (2)

Wrapping up

This article looked at data encryption and decryption in Node.js using the crypto module. Also, it touched on:

  • Cryptography in Node.js.
  • Node.js crypto module.

I hope you’ve gained a solid knowledge about encryption and decryption and how to use the crypto module in Node.js applications to implement encryption and decryption.

Peer Review Contributions by: Mohan Raj

FAQs

How do I encrypt and decrypt data in node JS? ›

Encrypt and decrypt streams

const crypto = require('crypto'); const fs = require('fs'); const algorithm = 'aes-256-ctr'; const secretKey = 'vOVH6sdmpNWjRRIqCc7rdxs01lwHzfr3'; const iv = crypto. randomBytes(16); // input file const r = fs. createReadStream('file. txt'); // encrypt content const encrypt = crypto.

What is crypto used for in node JS? ›

The node:crypto module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.

How do you encrypt data in node JS? ›

// crypto module const crypto = require("crypto"); const algorithm = "aes-256-cbc"; // generate 16 bytes of random data const initVector = crypto. randomBytes(16); // protected data const message = "This is a secret message"; // secret key generate 32 bytes of random data const Securitykey = crypto. randomBytes(32);

What is encryption and decryption in cryptography? ›

Encryption is the process by which a readable message is converted to an unreadable form to prevent unauthorized parties from reading it. Decryption is the process of converting an encrypted message back to its original (readable) format.

Is crypto included in Nodejs? ›

Crypto is a module in Node. js which deals with an algorithm that performs data encryption and decryption. This is used for security purpose like user authentication where storing the password in Database in the encrypted form. Crypto module provides set of classes like hash, HMAC, cipher, decipher, sign, and verify.

Is crypto built into Nodejs? ›

crypto is built into Node. js, so it doesn't require rigorous implementation process and configurations. Unlike other modules, you don't need to install Crypto before you use it in your Node. js application.

How do you hash a password using crypto in node js? ›

  1. First create a directory structure as below : hashApp --model ----user.js --route ----user.js --server.js.
  2. Create model/user.js file which defines user schema. ...
  3. Create route/user.js file : ...
  4. Run server.js file using command node server.js from the hashApp directory.
11 Jul 2022

How do I create a cryptocurrency payment system in node js? ›

Implementing a crypto payment gateway using NodeJS
  1. Step 1: Create a Coinbase Commerce account. ...
  2. Step 2: Initialize back-end. ...
  3. Step 3: Installing the necessary packages. ...
  4. Step 4: Set up environment variables. ...
  5. Step 5: Requiring the dependencies. ...
  6. Step 6: Create charge route. ...
  7. Step 7: Check the status of the payment.
27 Dec 2021

What is crypto in JavaScript? ›

Crypto-JS is a growing collection of standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns. They are fast, and they have a consistent and simple interface.

How do I encrypt and decrypt JSON data in node JS? ›

The code for my encryption is supposedly like this: const encrypted = key. encrypt(data, 'base64'); res. json({ status: 200, message: "Done", data: encrypted; });

How do you use crypto js in react? ›

To encrypt and decrypt data, simply use encrypt() and decrypt() function from an instance of crypto-js. var bytes = CryptoJS. AES. decrypt(ciphertext, 'my-secret-key@123');

What is cryptography used for? ›

Cryptography provides for secure communication in the presence of malicious third-parties—known as adversaries. Encryption uses an algorithm and a key to transform an input (i.e., plaintext) into an encrypted output (i.e., ciphertext).

What is decrypting Crypto? ›

It involves the conversion of unreadable data (ciphertext) into readable (plaintext). So while encryption is the process of making data unreadable, decryption is the process of converting the encrypted information back to its original and understandable form.

What is encryption and decryption with examples? ›

Encryption is the process of translating plain text data (plaintext) into something that appears to be random and meaningless (ciphertext). Decryption is the process of converting ciphertext back to plaintext. To encrypt more than a small amount of data, symmetric encryption is used.

How do I get node crypto? ›

#Buidl
  1. Step 1: Hardware. I decided to run my Bitcoin full node using Raspberry Pi 3+. ...
  2. Step 2: Choose what OS you want to run. ...
  3. Step 3: Set up the hardware/OS. ...
  4. Step 4: Install Bitcoin. ...
  5. Step 5: Configure your router to allow port 8333 on TCP/UDP protocol. ...
  6. Step 6: Verify that your Bitcoin Node can be reached.

What is hashing in node JS? ›

The hash. digest( ) method is an inbuilt function of the crypto module's Hash class. This is used to create the digest of the data which is passed when creating the hash. For example, when we create a hash we first create an instance of Hash using crypto.

How do I encrypt a string in node JS? ›

Encrypt and Decrypt String using Node JS and Mongo DB - YouTube

Do I need to NPM install crypto? ›

If you are using the methods from the Crypto module that comes with NodeJS, i.e. those described on http://nodejs.org/api/crypto.html then no, you do not need to do npm install crypto .

How does AES 128 encryption work? ›

The AES Encryption algorithm (also known as the Rijndael algorithm) is a symmetric block cipher algorithm with a block/chunk size of 128 bits. It converts these individual blocks using keys of 128, 192, and 256 bits. Once it encrypts these blocks, it joins them together to form the ciphertext.

How do I decode HMAC sha256? ›

First, enter the plain-text and the cryptographic key to generate the code. Then, you can use select the hash function you want to apply for hashing. The default is SHA-256. Then you can submit your request by clicking on the compute hash button to generate the HMAC authentication code for you.

What is better than bcrypt? ›

SCrypt is a better choice today: better design than BCrypt (especially in regards to memory hardness) and has been in the field for 10 years. On the other hand, it has been used for many cryptocurrencies and we have a few hardware (both FPGA and ASIC) implementation of it.

How HMAC works explain? ›

Hash-based Message Authentication Code (HMAC) is a message authentication code that uses a cryptographic key in conjunction with a hash function. Hash-based message authentication code (HMAC) provides the server and the client each with a private key that is known only to that specific server and that specific client.

What is bcrypt in NodeJS? ›

bcrypt is an npm module that simplifies password salting and hashing.

How do I create a crypto network? ›

Create your own blockchain and native cryptocurrency. Modify the code of an existing blockchain.
...
If you decide that building a new blockchain is your next step, then here's what you need to do:
  1. Choose a consensus mechanism. ...
  2. Design your blockchain architecture. ...
  3. Audit your new blockchain and its code.

How do you code cryptocurrency? ›

Ways to Create a Cryptocurrency
  1. Create a New Blockchain. ...
  2. Fork an Existing Blockchain. ...
  3. Use an Existing Platform. ...
  4. Decide on a Consensus Mechanism. ...
  5. Choose a Blockchain. ...
  6. Create the Nodes. ...
  7. Build the Blockchain Architecture. ...
  8. Integrate APIs.
19 Aug 2021

How do I create a crypto payment gateway? ›

develop a cryptocurrency payment solution from scratch. register a crypto wallet and publish its public address. create a crypto coin or token. integrate with an existing blockchain payment solution provider.
...
Get a crypto wallet
  1. uncertainty with regulations (Can I accept it in my legislation? ...
  2. manual orders processing.
27 Oct 2021

Is crypto js secure? ›

CryptoJS is a growing collection of standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns. They are fast, and they have a consistent and simple interface.

What is a Crypto API? ›

The Web Crypto API is an interface allowing a script to use cryptographic primitives in order to build systems using cryptography.

Is JavaScript crypto safe? ›

With JavaScript's web cryptography API in place, the server can't see data since it's cryptographically secure. Only the sender and receiver have access to communication data.

What is IV in crypto js? ›

createCipheriv() Method. The crypto. createCipheriv() method is an inbuilt application programming interface of the crypto module which is used to create a Cipher object, with the stated algorithm, key and initialization vector (iv).

How do you encrypt and decrypt? ›

How to Encrypt and Decrypt a File
  1. Create a symmetric key of the appropriate length. You have two options. You can provide a passphrase from which a key will be generated. ...
  2. Encrypt a file. Provide a key and use a symmetric key algorithm with the encrypt command.

What is IV in cryptography? ›

An initialization vector (IV) is an arbitrary number that can be used along with a secret key for data encryption. This number, also called a nonce, is employed only one time in any session.

How do you encrypt CryptoJS AES? ›

Crypto-js also provides the functionality to encrypt and decrypt objects in a deep level.
  1. var data = [{ foo: bar }, { bar: foo}];
  2. var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'secret key 123');
  3. var bytes = CryptoJS.AES.decrypt(ciphertext.toString(), 'secret key 123');
1 Jun 2020

How do I use JSEncrypt? ›

JS
  1. document. querySelector("#encrypt"). addEventListener("click", function() {
  2. const encrypt = new JSEncrypt();
  3. encrypt. setPublicKey(document. querySelector("#pubkey"). ...
  4. const result = encrypt. encrypt(document. querySelector("#input"). ...
  5. document. querySelector("#encrypted"). ...
  6. document. querySelector("#decrypt").

How do I encrypt data in react native? ›

A hybrid approach to safely store user data
  1. Create a secure key using react-native-keychain . That's the key we'll use to encrypt our data. ...
  2. Turn our store data into an easily encrypt-able format, ie. using JSON. ...
  3. Encrypt our data using the generated secure key 🔐
  4. Write the encrypted blob of data to our unencrypted store.

What are the 3 main types of cryptographic algorithms? ›

There are three general classes of NIST-approved cryptographic algorithms, which are defined by the number or types of cryptographic keys that are used with each.
  • Hash functions.
  • Symmetric-key algorithms.
  • Asymmetric-key algorithms.
  • Hash Functions.
  • Symmetric-Key Algorithms for Encryption and Decryption.
29 Oct 2019

What are the 2 types of cryptography? ›

Cryptography can be broken down into three different types: Secret Key Cryptography. Public Key Cryptography. Hash Functions.

What are the three types of encryption? ›

The three major encryption types are DES, AES, and RSA. While there are many kinds of encryption - more than can easily be explained here - we will take a look at these three significant types of encryption that consumers use every day.

What is the most secure cryptographic algorithm? ›

The Advanced Encryption Standard, AES, is a symmetric encryption algorithm and one of the most secure. The United States Government use it to protect classified information, and many software and hardware products use it as well.

What is cryptography algorithm? ›

Cryptography algorithms are the means of altering data from a readable form to a protected form and back to the readable form. Cryptographic algorithms are used for important tasks such as data encryption, authentication, and digital signatures.

What is the strongest encryption method? ›

AES 256-bit encryption is the strongest and most robust encryption standard that is commercially available today. While it is theoretically true that AES 256-bit encryption is harder to crack than AES 128-bit encryption, AES 128-bit encryption has never been cracked.

What is difference between encryption and decryption? ›

Encryption is the process that converts plain text into the coded one that appears to be meaningless, i.e., cipher text. Whereas, decryption is the process that converts ciphertext into plaintext.

Can you decrypt blockchain? ›

Compromising and taking control of the Bitcoin network is a challenging prospect. That's because Bitcoin is cryptographic, irreversible, distributed, and public. Brute-forcing private keys, or hijacking the blockchain by controlling 50% of the network's computing power, are all but impossible.

What is encryption in blockchain? ›

Cryptography is a method of securing data from unauthorized access. In the blockchain, cryptography is used to secure transactions taking place between two nodes in a blockchain network. As discussed above, in a blockchain there are two main concepts cryptography and hashing.

What is the difference between encryption and cryptography? ›

Encryption is the method by which information is converted into secret code that hides the information's true meaning. The science of encrypting and decrypting information is called cryptography. In computing, unencrypted data is also known as plaintext, and encrypted data is called ciphertext.

What are the types of decryption? ›

Cyber Security Awareness
  • Symmetric Decryption − In symmetric encryption, the same mathematical equation both encrypts and decrypts the information. ...
  • Asymmetric Decryption − Asymmetric decryption methods also known as public-key decryption.
15 Mar 2022

What are two basic functions used in encryption algorithms? ›

Substitution and transposition are the two basic functions used in encryption algorithms.

How do I encrypt and decrypt JSON data in node JS? ›

The code for my encryption is supposedly like this: const encrypted = key. encrypt(data, 'base64'); res. json({ status: 200, message: "Done", data: encrypted; });

How do you encrypt and decrypt? ›

How to Encrypt and Decrypt a File
  1. Create a symmetric key of the appropriate length. You have two options. You can provide a passphrase from which a key will be generated. ...
  2. Encrypt a file. Provide a key and use a symmetric key algorithm with the encrypt command.

What is Bcrypt in node JS? ›

bcrypt is an npm module that simplifies password salting and hashing.

What is hashing in node JS? ›

The hash. digest( ) method is an inbuilt function of the crypto module's Hash class. This is used to create the digest of the data which is passed when creating the hash. For example, when we create a hash we first create an instance of Hash using crypto.

How do you use crypto-js in react? ›

To encrypt and decrypt data, simply use encrypt() and decrypt() function from an instance of crypto-js. var bytes = CryptoJS. AES. decrypt(ciphertext, 'my-secret-key@123');

What is IV in crypto-js? ›

createCipheriv() Method. The crypto. createCipheriv() method is an inbuilt application programming interface of the crypto module which is used to create a Cipher object, with the stated algorithm, key and initialization vector (iv).

What is IV in cryptography? ›

An initialization vector (IV) is an arbitrary number that can be used along with a secret key for data encryption. This number, also called a nonce, is employed only one time in any session.

What is encryption and decryption with examples? ›

Encryption is the process of translating plain text data (plaintext) into something that appears to be random and meaningless (ciphertext). Decryption is the process of converting ciphertext back to plaintext. To encrypt more than a small amount of data, symmetric encryption is used.

What is the difference between encryption and cryptography? ›

Encryption is the method by which information is converted into secret code that hides the information's true meaning. The science of encrypting and decrypting information is called cryptography. In computing, unencrypted data is also known as plaintext, and encrypted data is called ciphertext.

What is JWT in node JS? ›

JWTs are mainly used for authentication. After a user signs in to an application, the application then assigns JWT to that user. Subsequent requests by the user will include the assigned JWT. This token tells the server what routes, services, and resources the user is allowed to access.

Is bcrypt better than sha256? ›

Bcrypt was not designed for encrypting large amounts of data. It is best implemented for passwords, however SHA-256 is better for large amounts of data because it is less costly and faster.

Is bcrypt a hash or encryption? ›

bcrypt is a password-hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher and presented at USENIX in 1999.

How do you hash a password using crypto in node JS? ›

  1. First create a directory structure as below : hashApp --model ----user.js --route ----user.js --server.js.
  2. Create model/user.js file which defines user schema. ...
  3. Create route/user.js file : ...
  4. Run server.js file using command node server.js from the hashApp directory.
11 Jul 2022

What is SHA1 and SHA256? ›

SHA1 is a first version of SHA that generates a 160-bit hash value. SHA256 is type of SHA2 that generates a 256-bit hash value. 2. The internal state size of SHA1 is 160. The internal state size of SHA256 is 256.

What is MD5 in node JS? ›

MD5 stands for message digest 5 is a widely used hash function which produces 128-bit hashes. We are generating a simple hash using md5 hashing algorithm of node.js. Code. //md5-hash.js //Loading the crypto module in node.js var crypto = require('crypto'); //creating hash object var hash = crypto.

Videos

1. Mysql Store Encryption and Decryption in Node.js using Crypto Curl Api
(Code Solution)
2. NodeJS - Crypto-JS Library
(Ambrish Jha)
3. Asymmetric Encryption and Decryption in Node.js using RSA Public/Private Key Pairs
(Techno Saviour)
4. Error: Cannot find module 'bcrypt' | Encrypt and Decrypt Data in Node.js with crypto module
(Tech Forum)
5. CryptoJS In JavaScript - how to encrypt or secure cookie data sessionStorage data or localStorage
(wap institute)
6. Data Encryption with CryptoJS
(Postman)

You might also like

Latest Posts

Article information

Author: Delena Feil

Last Updated: 07/06/2022

Views: 5795

Rating: 4.4 / 5 (45 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Delena Feil

Birthday: 1998-08-29

Address: 747 Lubowitz Run, Sidmouth, HI 90646-5543

Phone: +99513241752844

Job: Design Supervisor

Hobby: Digital arts, Lacemaking, Air sports, Running, Scouting, Shooting, Puzzles

Introduction: My name is Delena Feil, I am a clean, splendid, calm, fancy, jolly, bright, faithful person who loves writing and wants to share my knowledge and understanding with you.