Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
What is the purpose of module.exports in node.js ?
Next article icon

What is Crypto Module in Node.js and How it is used ?

Last Updated : 14 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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. This module enables you to perform various security operations, such as hashing, encryption, and decryption, directly in your Node.js applications. In this article, we will explore what the crypto module is, its key features, and how to use it to perform common cryptographic operations.

What is the Crypto Module?

The crypto module in Node.js is part of the core libraries, meaning it is built into Node.js and does not require any external dependencies. It provides a way to perform cryptographic operations such as:

  • Hashing data to produce fixed-size digests.
  • Encrypting and decrypting data using symmetric and asymmetric algorithms.
  • Generating cryptographic signatures and verifying them.
  • Creating secure random numbers and keys.

These capabilities make the crypto module an essential tool for developing secure applications that require data integrity, confidentiality, and authentication.

Key Features of the Crypto Module

  • Hashing and HMAC: Create fixed-size digests from arbitrary-sized data, useful for data integrity and verification.
  • Symmetric Encryption: Encrypt and decrypt data using the same key.
  • Asymmetric Encryption: Encrypt and decrypt data using a key pair (public and private keys).
  • Digital Signatures: Generate and verify signatures for data, ensuring authenticity and integrity.
  • Random Number Generation: Generate cryptographically secure random numbers and keys.
  • Password-Based Key Derivation: Securely derive cryptographic keys from passwords.

Plain text:

Anything that we write or type which is humanly understandable is called plain text. It can contain any character(a-zA-Z0-9!,@,#....). Eg. our password

Ciphertext:

sdfasc1asT67W2sqWwsdfsadf Are you able to understand this word? This was a ciphertext is, a nonreadable and nonunderstandable text which is generated by passing plain text through an algorithm.  

The Mechanism in Cryptography:

Hashing

This is a mechanism to convert a plain text to ciphertext. It is a one-way cryptographic function i.e, we can't convert cipher text to plain text. It is widely used in authentication systems to avoid storing plain text passwords in databases but is also used to validate files, documents, and other types of data.  Message Digest 5(MD5), RSA, SHA, etc are Widely used algorithms for hashing.

Encryption and Decryption

Encryption algorithms take input and a secret key and generate a random-looking output called a ciphertext. This operation is reversible. Decryption is the reverse of encryption. This algorithm takes the same secret key and ciphertext and it returns back our original plain text. This is widely used in messaging systems like WhatsApp etc.  AES, etc are Widely used algorithms for encryption and decryption.

Features of Crypto in Node.js

  • It’s easy to get started
  • A lot of widely used algorithms are there with different versions
  • The source code is cleaner and consistent.
  • It uses JavaScript everywhere so you can use it with node.js

Installing module:

npm install crypto-js --save

Project Structure:


Screenshot-2024-06-13-152451

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.19.2",
}

we can use this module in two ways either for the hashing or either use in encryption and decryption of the data. There are a lot of algorithms available for hashing as well as encryption and decryption of the data.

Using a crypto module for Hashing the data:

Node
// index.js  // Importing module const SHA256 = require("crypto-js/sha256"); const plaindata = "GeeksForGeeks" const hasheddata = SHA256(plainText).toString() console.log(hasheddata) 

Step to Run Application: Run the application using the following command from the root directory of the project

node index.js

Output:

Using a crypto module for encryption and decryption of the data:

We will use the key for encryption and decryption of the data. A single key can be used for the encryption of the data as well as in the decryption process of the data. Below is an example of the encryption and decryption of the data using a single key.

Node
// index.js  // Importing the crypto module const crypto = require("crypto-js") const data = "This is the data that need to be encrypted" const key = "password@111"  // Encrypte the data const encrypted = crypto.AES.encrypt(data, key).toString(); console.log("Encrypted data")  // Printing the encrypted data console.log(encrypted) console.log("Decrypted data")  // Decrypting the data const decrypted = crypto.AES.decrypt(encrypted, key)                                     .toString(crypto.enc.Utf8) console.log(decrypted) 

Step to Run Application: Run the application using the following command from the root directory of the project

node index.js

Output:


Next Article
What is the purpose of module.exports in node.js ?
author
zack_aayush
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Blogathon
  • Blogathon-2021
  • Node.js-crypto-module
  • NodeJS-Questions

Similar Reads

  • How to use EcmaScript Modules in Node.js ?
    Using ECMAScript Modules (ES Modules or ESM) in Node.js allows you to take advantage of modern JavaScript syntax for organizing and managing your code. ECMAScript Modules provide a more structured and standardized way to work with modules compared to CommonJS, which has been traditionally used in No
    2 min read
  • Node JS | Password Hashing with Crypto module
    In real-life applications with User authentication functionality, storing the user passwords as the original string in the database is not practical. Still, it is good practice to hash the password and then store them in the database. Crypto module for Node JS helps developers to hash user passwords
    5 min read
  • What is File System Module in Node.js ?
    Node.js is a powerful platform for building server-side applications, and one of its key features is its ability to interact with the file system. The File System (fs) module in Node.js provides an extensive API to work with files and directories, allowing developers to perform operations such as re
    3 min read
  • What is the purpose of module.exports in node.js ?
    The module.exports is actually a property of the module object in node.js. module. Exports is the object that is returned to the require() call. By module.exports, we can export functions, objects, and their references from one file and can use them in other files by importing them by require() meth
    3 min read
  • Explain the use of crypto module in Node.js
    In this article, we will explore the crypto module and what are its uses in Node.js. NodeJS supports a large number of third-party modules. These modules can be used for performing different kinds of tasks. The crypto module is also a 3rd party module that can be imported and used in NodeJS. This mo
    3 min read
  • What are modules in Node JS ?
    In NodeJS, modules are encapsulated units of code that can be reused across different parts of an application. Modules help organize code into smaller, manageable pieces, promote code reusability, and facilitate better maintainability and scalability of NodeJS applications. Types of Modules:Core Mod
    2 min read
  • What are Modules in Node.js ?
    In Node.js Application, a Module can be considered as a block of code that provide a simple or complex functionality that can communicate with external application. Modules can be organized in a single file or a collection of multiple files/folders. Almost all programmers prefer modules because of t
    5 min read
  • Which module is used for buffer based operations in Node.js ?
    The module which is used for buffer-based operation is the buffer module. Buffer Module: The buffers module provides a way of handling streams of binary data. Buffers are designed to handle binary raw data. Buffers allocate raw memory outside the V8 heap. The Buffer object is a global object in Node
    2 min read
  • How to write code using module.exports in Node.js ?
    module is a discrete program, contained in a single file in Node.js. They are tied to files with one module per file. module.exports is an object that the current module returns when it is "required" in another program or module. We are going to see a simple code like the calculator to learn how to
    3 min read
  • What are the differences between HTTP module and Express.js module ?
    HTTP and Express both are used in NodeJS for development. In this article, we'll go through HTTP and express modules separately HTTP: It is an in-build module which is pre-installed along with NodeJS. It is used to create server and set up connections. Using this connection, data sending and receivi
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences