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:
Password Encryption in Node.js using bcryptjs Module
Next article icon

Node JS | Password Hashing with Crypto module

Last Updated : 27 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 

Examples:

Original Password : portalforgeeks Hashed Password : bbf13ae4db87d475ca0ee5f97e397248a23509fc10c82f 1e3cf110b352c3ca6cc057955ace9d541573929cd7a74a 280a02e8cb549136b43df7704caaa555b38a

Password Hashing with Crypto module:

To demonstrate the use of the Crypto module, we can create a simple login and signup API and test it using Postman. We will use two functions:

  • crypto.randomBytes(“length”): generates cryptographically strong data of given “length”.
  • crypto.pbkdf2Sync(“password”, “salt”, “iterations”, “length”, “digest”): hashes “password” with “salt” with a number of iterations equal to given “iterations” (More iterations means more secure key) and uses algorithm given in “digest” and generates key of length equal to given “length”.

Project Dependencies:

  • node JS: For Backend Server.
  • express module for creating the server.
  • mongoose module for MongoDB connection and queries.
  • Crypto module for hashing.
  • body-parser for parsing JSON data.

Let’s develop a simple nodejs server:

Step 1: Create a project folder

Step 2: Create package.json

Package.json will be created by typing the following command in the terminal or command prompt:

npm init -y

Project Directory:

hashApp --model ----user.js --route ----user.js --server.js

Create model/user.js file which defines user schema 

javascript




// Importing modules
const mongoose = require('mongoose');
const crypto = require('crypto');
 
// Creating user schema
const UserSchema = mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    hash: String,
    salt: String
});
 
// Method to set salt and hash the password for a user
// setPassword method first creates a salt unique for every user
// then it hashes the salt with user password and creates a hash
// this hash is stored in the database as user password
UserSchema.methods.setPassword = function (password) {
 
    // Creating a unique salt for a particular user
    this.salt = crypto.randomBytes(16).toString('hex');
 
    // Hashing user's salt and password with 1000 iterations,
    64 length and sha512 digest
    this.hash = crypto.pbkdf2Sync(password, this.salt,
        1000, 64, `sha512`).toString(`hex`);
};
 
// Method to check the entered password is correct or not
// valid password method checks whether the user
// password is correct or not
// It takes the user password from the request
// and salt from user database entry
// It then hashes user password and salt
// then checks if this generated hash is equal
// to user's hash in the database or not
// If the user's hash is equal to generated hash
// then the password is correct otherwise not
UserSchema.methods.validPassword = function (password) {
    var .hash = crypto.pbkdf2Sync(password,
        this.salt, 1000, 64, `sha512`).toString(`hex`);
    return this.hash === hash;
};
 
// Exporting module to allow it to be imported in other files
const User = module.exports = mongoose.model('User', UserSchema);
 
 

Create route/user.js file : 

javascript




// Importing modules
const express = require('express');
const router = express.Router();
 
// Importing User Schema
const User = require('../model/user');
 
// User login api
router.post('/login', (req, res) => {
 
    // Find user with requested email
    User.findOne({ email: req.body.email }, function (err, user) {
        if (user === null) {
            return res.status(400).send({
                message: "User not found.";
            });
        }
        else {
            if (user.validPassword(req.body.password)) {
                return res.status(201).send({
                    message: "User Logged In";,
                })
            }
            else {
                return res.status(400).send({
                    message: "Wrong Password";
                });
            }
        }
    });
});
 
// User signup api
router.post('/signup', (req, res, next) => {
 
    // Creating empty user object
    let newUser = new User();
 
    // Initialize newUser object with request data
    newUser.name = req.body.name,
 
        newUser.email = req.body.email
 
    // Call setPassword function to hash password
    newUser.setPassword(req.body.password);
 
    // Save newUser object to database
    newUser.save((err, User) => {
        if (err) {
            return res.status(400).send({
                message: "Failed to add user."
            });
        }
        else {
            return res.status(201).send({
                message: "User added successfully."
            });
        }
    });
});
 
// Export module to allow it to be imported in other files
module.exports = router;
 
 

Create server.js file : 

javascript




// Importing modules
const express = require('express');
const mongoose = require('mongoose');
const bodyparser = require('body-parser');
 
// Initialize express app
const app = express();
 
// Mongodb connection url
const MONGODB_URI = "mongodb://localhost:27017/hashAppDb";
 
// Connect to MongoDB
mongoose.connect(MONGODB_URI);
mongoose.connection.on('connected', () => {
    console.log('Connected to MongoDB @ 27017');
});
 
// Using bodyparser to parse json data
app.use(bodyparser.json());
 
// Importing routes
const user = require('./route/user');
 
// Use user route when url matches /api/user/
app.use('/api/user', user);
 
// Creating server
const port = 3000;
app.listen(port, () => {
    console.log("Server running at port:" + port);
});
 
 

Run the server.js file using the command node server.js from the hashApp directory

node server.js 

If you have nodemon installed in your system then it can also be done by using the following link:

nodemon server.js

Open Postman and create a post request to localhost:3000/api/user/signup as below: You will get the response below:

  

User data is stored in the database as below:

{     "_id": {         "$oid": "5ab71ef2afb6db0148052f6f"     },     "name": "geeksforgeeks",     "email": "[email protected]",     "salt": "ddee18ef6a6804fbb919b25f790005e3",     "hash": "bbf13ae4db87d475ca0ee5f97e397248a23509fc10c82f1e3cf110      b352c3ca6cc057955ace9d541573929cd7a74a280a02e8cb549136b43df7704caaa555b38a",     "__v": 0 }

From Postman create a post request to localhost:3000/api/user/login as below: 

You will get the response below:

 

Applications:

  • Hashing password is necessary for practical application.
  • Crypto module makes hashing easy to implement.
  • Hashing passwords ensures user privacy.

References:

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


Next Article
Password Encryption in Node.js using bcryptjs Module

N

neerajnegi174
Improve
Article Tags :
  • JavaScript
  • Node.js
  • Technical Scripter
  • Web Technologies

Similar Reads

  • Password Hashing with MD5 module in Node.js
    MD5 module in node.js uses a message-digest algorithm and it is a widely used hash function producing a 128-bit hash value. Password hashing is an important concept because, in the database, the actual password should not be stored as its a bad practice and also make the system less secure, so the p
    2 min read
  • Password Encryption in Node.js using bcryptjs Module
    When developing applications, one of the critical aspects of user authentication is ensuring that passwords are stored securely. Plain text storage of passwords is a significant security risk. Instead, passwords should be encrypted using strong hashing algorithms. In Node.js, one of the popular modu
    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 is Crypto Module in Node.js and How it is used ?
    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
    4 min read
  • How to Hash String with md5 Function in Node.js ?
    Hashing means taking any string as a key and generating some other string for it as a value. It's like key-value pair in maps or dictionaries. md5 hash is an encryption algorithm that takes the various bits of a file and outputs a unique text string. md5 is a one-way encryption algorithm, i.e. there
    2 min read
  • Node.js crypto.scrypt() Method
    The crypto.scrypt() method is an inbuilt application programming interface of the crypto module which is used to enable an implementation of an asynchronous script. Where scrypt is a password-based key derivation function. It is intended to be costly computationally plus memory-wise. So, the brute-f
    4 min read
  • Node.js crypto.getHashes() Method
    The crypto.getHashes() method is an inbuilt application programming interface of crypto module which is used to display the names of all the supported hash algorithms in an array. Syntax: crypto.getHashes() Parameters: This method doesn't accept any parameters. Return Value: It returns the name of a
    1 min read
  • Node.js crypto.randomInt() Method
    The Crypto.randomInt method in Node.js is an inbuilt application programming interface of the crypto module which is used to create a random integer synchronously or asynchronously based on our usage. Syntax: crypto.randomInt([min, ] max [, callback]) Parameters: This method accepts three parameters
    2 min read
  • Node.js crypto.hkdfSync( ) Method
    This method provides a synchronous HMAC-based Extract-and-Expand Key Derivation Function key derivation. Key of keylen bytes is derived using digest, given key, salt and info. Syntax: crypto.hkdfSync(digest, key, salt, info, keylen) Parameters: This method has five parameters. digest: It must be str
    2 min read
  • Node.js crypto.pbkdf2() Method
    The crypto.pbkdf2() method gives an asynchronous Password-Based Key Derivation Function 2 i.e. (PBKDF2) implementation. Moreover, a particular HMAC digest algorithm which is defined by digest is implemented to derive a key of the required byte length (keylen) from the stated password, salt, and iter
    2 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