NodeJS Crypto Module - Encrypt and Decrypt Data | CodeForGeek (2024)

NodeJS Crypto is a built-in module used to perform several types of encryption and decryption.

NodeJS is used to create many applications, and some contain confidential information that should be highly secure. To secure that information, it is required to encrypt them so that a hacker or outsider can not be able to understand it.

Encrypt means converting the information into a form that is not understandable to others. The processing of converting plain text into encrypted format is called encryption.

Let’s understand the uses of encryption with an example. Suppose we are creating a website where we ask for a username and password and we store that data in a database to authenticate the user when they come again. But the database used is stored in a third-party cloud and it can be hacked and the user’s password and username can be leaked.

This is called a data breach.

To ensure that even after the data breach:

  • the password is safe, we have to encrypt them into a form that hackers can not understand.
  • When a user comes and login we just encrypt the entered password with the same algorithm.
  • Then we match it with the encrypted one in our database.
  • If it is the same, then authenticate the users.

Let’s understand how we can do so using the NodeJS crypto module.

Node.js Crypto Module

Node.js Crypto Module can be imported using the below statement.

Syntax

const crypto = require('crypto');

Data Encryption Using Node.js Crypto Module

The Node.js Crypto Module provides the createCiphervie method for converting plain text into cipher text. This method takes three arguments to create a cipher object which is then used to encrypt the plain text.

List of arguments used by the createCiphervie method.

  1. Algorithm – There are various algorithms that can to used to encrypt passwords, and for again decrypting the password it is mandatory to use the same algorithm.
  2. Key – A key is a unique value that must be the same for encryption and decryption, this ensures that either hacker knows the algorithm they are not able to decrypt the encrypted text because the key is unknown to them.
  3. IV – The last argument is an IV, initialization vector, used with the key to performing encryption and description.

Syntax:

crypto.createCipheriv(algorithm, key, iv);

The procedure of encryption using Node.js Crypto Module

  1. We will start with importing the crypto module.
  2. Initiate a constant containing the algorithm we want to use.
  3. Generate random key and IV.
  4. Create a function with takes text as an argument.
  5. Inside the function use the createCiphervie method and pass the algorithm, key, and IV, then set it to a variable cipher.
  6. Use the cipher variable to update the text passed as an argument, this will convert the plain text into encrypted text.
  7. Then concatenate the encrypted text and use cipher.final() method.
  8. Return an object containing the IV and encrypted text.

Example:

Let’s encrypt a string “Hello World!” using the above procedure.

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(algorithm, Buffer.from(key), iv); let encrypted = cipher.update(text); encrypted = Buffer.concat([encrypted, cipher.final()]); return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };}var encrypted = encrypt("Hello World!");console.log("Encrypted Text: " + encrypted.encryptedData);

Output:

Encrypted Text: bd694d9bcf99f1268c18231a9d856a38

Decryption using Node.js Crypto Module

For decryption, the Node.js Crypto module provides a method createDeciphervie which works exactly the same as createCiphervie.

Syntax:

crypto.createDecipheriv(algorithm, key, iv);

The procedure of decryption using Node.js Crypto Module

  1. Create a function with takes encrypted data as an argument.
  2. Fetch the IV and encrypted text from the data pass as an argument.
  3. Use the createDeciphervie method and pass the algorithm, key, and IV then set the function to a variable decipher.
  4. Use the decipher variable to update the decrypted text.
  5. Then concatenate the decrypted text and use decipher.final() method.
  6. Return the plain text.

Example:

We use the data gets as an output of encrypt method and then decrypt it to get the plain text. For getting the exact same plain text, the algorithm, key, and IV must be the same.

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(algorithm, Buffer.from(key), iv); let encrypted = cipher.update(text); encrypted = Buffer.concat([encrypted, cipher.final()]); return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };}var encrypted = encrypt("Hello World!");function decrypt(text) { let iv = Buffer.from(text.iv, 'hex'); let encryptedText = Buffer.from(text.encryptedData, 'hex'); let decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), iv); let decrypted = decipher.update(encryptedText); decrypted = Buffer.concat([decrypted, decipher.final()]); return decrypted.toString();}const decrypted = decrypt(encrypted)console.log("Decrypted Text: " + decrypted); 

Output:

Decrypted Text: Hello World!

Summary

Node.js Crypto is used for encryption and description to ensure the confidentiality of a message. It can be used to encrypt the password and important data. It can also be used when creating a chat application to encrypt the message before sending it so that it can’t be read by a hacker. Hope this article will help you to understand the processor of encryption and decryption using the Node.js Crypto module.

Reference

https://nodejs.org/api/crypto.html#crypto

NodeJS Crypto Module - Encrypt and Decrypt Data | CodeForGeek (2024)

FAQs

How to encrypt and decrypt using crypto? ›

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.

How to encrypt with crypto in nodejs? ›

randomBytes(32); //The cipher function const cipher = crypto. createCipheriv(algorithm, Securitykey, initVector); //Encrypt the message // input encoding // output encoding let encryptedData = cipher. update(message, "utf-8", "hex"); The final() method helps the cipher to stop the encryption process by the code here.

How to encrypt and decrypt data in js? ›

To encrypt and decrypt data, simply use encrypt() and decrypt() methods respectively. This will use AES-256-CBC encryption algorithm as the mid-channel cipher.

How to decrypt password in node? ›

export const decrypt = (encrypted: string) => { let decipher = crypto. createDecipheriv('aes-256-ecb', SECRET_ENCRYPT_KEY, null); let decrypted = decipher. update(encrypted, 'base64', 'utf8'); return decrypted + decipher.

What is the hardest encryption to decrypt? ›

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 encryption algorithm is used in cryptocurrency? ›

What cryptography does Bitcoin use? Bitcoin uses elliptic curve cryptography (ECC) and the Secure Hash Algorithm 256 (SHA-256) to generate public keys from their respective private keys.

What is the crypto module 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.

Does Node.js support cryptography? ›

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

How do I encrypt my Blockchain data? ›

When one of the participants needs to add a new data item to the blockchain, they first symmetrically encrypt it using the secret key. Then the transaction with the encrypted data is submitted to the blockchain.

Is CryptoJS 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 the difference between GCM and CBC? ›

Authentication Tag: - CBC: CBC mode does not generate an authentication tag. Any modification to the ciphertext will likely lead to decryption errors, but it won't be detected during decryption. - GCM: GCM mode generates an authentication tag, which is used to verify data integrity during decryption.

How can encrypted data be decrypted? ›

Obtain the decryption key associated with the encrypted data. Launch the decryption software or tool compatible with the encryption algorithm used. Import the decryption key into the software or tool. Select the encrypted file or folder you want to decrypt.

What is the NodeJS library for encryption and decryption? ›

NodeJS provides inbuilt library crypto to encrypt and decrypt data in NodeJS. We can use this library to encrypt data of any type. You can do the cryptographic operations on a string, buffer, and even a stream of data.

Which cryptographic algorithm is best? ›

The Advanced Encryption Standard (AES) is the trusted standard algorithm used by the United States government, as well as other organizations. Although extremely efficient in the 128-bit form, AES also uses 192- and 256-bit keys for very demanding encryption purposes.

How to encrypt passwords in node js? ›

Approach
  1. The bcryptjs module is imported. A plain text password password is defined. ...
  2. bcrypt. genSalt(10, function (err, Salt) {...}) ...
  3. Inside the salt generation callback, bcrypt. ...
  4. If an error occurs, an error message is logged. ...
  5. bcrypt. ...
  6. If they match, logs indicate successful encryption and matching.
Jun 12, 2024

Can you encrypt cryptocurrency? ›

Cryptocurrency is stored in digital wallets. Cryptocurrency received its name because it uses encryption to verify transactions. This means advanced coding is involved in storing and transmitting cryptocurrency data between wallets and to public ledgers. The aim of encryption is to provide security and safety.

Can crypto be decrypted? ›

Use the Decryption Algorithm: To decrypt your crypto, you need to use the same encryption algorithm that was used to encrypt the data. Input the encryption key into the decryption algorithm to convert the ciphertext back into plaintext.

How do I decrypt an encrypted token? ›

  1. Navigate to the Decrypt Tool section of the Token Auth page.
  2. In the Token To Decrypt option, paste the desired token value.
  3. In the Key to Decrypt option, select the encryption key used to generate that token value.
  4. Click Decrypt. The requirements for that token will appear next to the Original Parameters label.

How do I encrypt and decrypt a file? ›

How to encrypt a file
  1. Right-click (or press and hold) a file or folder and select Properties.
  2. Select the Advanced button and select the Encrypt contents to secure data check box.
  3. Select OK to close the Advanced Attributes window, select Apply, and then select OK.

Top Articles
Top 10 Toughest Courses in India
Price-to-Earnings Ratios in the Real Estate Sector
Craigslist Myrtle Beach Motorcycles For Sale By Owner
Somboun Asian Market
Devon Lannigan Obituary
South Park Season 26 Kisscartoon
Wild Smile Stapleton
Elden Ring Dex/Int Build
Magic Mike's Last Dance Showtimes Near Marcus Cedar Creek Cinema
Grand Park Baseball Tournaments
Tiraj Bòlèt Florida Soir
shopping.drugsourceinc.com/imperial | Imperial Health TX AZ
Weekly Math Review Q4 3
Cranberry sauce, canned, sweetened, 1 slice (1/2" thick, approx 8 slices per can) - Health Encyclopedia
Bjork & Zhulkie Funeral Home Obituaries
Busted Newspaper S Randolph County Dirt The Press As Pawns
Funny Marco Birth Chart
Craigslist Panama City Fl
Troy Bilt Mower Carburetor Diagram
List of all the Castle's Secret Stars - Super Mario 64 Guide - IGN
Prestige Home Designs By American Furniture Galleries
Jalapeno Grill Ponca City Menu
Weepinbell Gen 3 Learnset
Kayky Fifa 22 Potential
Walgreens Alma School And Dynamite
Xsensual Portland
Encore Atlanta Cheer Competition
Where to eat: the 50 best restaurants in Freiburg im Breisgau
How to Watch Every NFL Football Game on a Streaming Service
His Only Son Showtimes Near Marquee Cinemas - Wakefield 12
Shia Prayer Times Houston
What is Software Defined Networking (SDN)? - GeeksforGeeks
How To Improve Your Pilates C-Curve
Gncc Live Timing And Scoring
Dubois County Barter Page
NIST Special Publication (SP) 800-37 Rev. 2 (Withdrawn), Risk Management Framework for Information Systems and Organizations: A System Life Cycle Approach for Security and Privacy
Nail Salon Open On Monday Near Me
Gideon Nicole Riddley Read Online Free
Viewfinder Mangabuddy
Bismarck Mandan Mugshots
Dying Light Nexus
Janaki Kalaganaledu Serial Today Episode Written Update
Sand Castle Parents Guide
Pekin Soccer Tournament
The power of the NFL, its data, and the shift to CTV
Unblocked Games - Gun Mayhem
Advance Auto.parts Near Me
Quest Diagnostics Mt Morris Appointment
Peugeot-dealer Hedin Automotive: alles onder één dak | Hedin
Lux Nails & Spa
Heisenberg Breaking Bad Wiki
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated:

Views: 6200

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.