The Wayback Machine - https://web.archive.org/web/20240616160443/https://www.geeksforgeeks.org/node-js-password-hashing-crypto-module/
Open In App

Node JS | Password Hashing with Crypto module

Last Updated : 27 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
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
 
// 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": "geek@geeksforgeeks.org",
    "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:



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 password is stored in hashed form into the database
2 min read
How to Generate Random and Unique Password in Node.js using 'generate-password' NPM Module ?
The "generate-password" module is a very useful and important external NPM module that can generate unique and random passwords for our projects. One of the main advantages of using this module is that it allows developers to easily generate passwords with various requirements, such as length, complexity, and character sets. This can save developer
2 min read
What is crypto module in Node.js and how it is used ?
Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 JavaScript engine for executing JavaScript code outside of a browser. Node.js supports a large number of third-party modules that help to perform many different kinds of tasks. Crypto module is one of the third-party modules that help encrypt or decrypt or hash an
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 module can be used for encrypting, decrypting, or ha
3 min read
How to Sign In with raw password when password store in the database are hashed form in Node.js ?
The password stored in the database is always in (hashed+salt) form because of security reasons. When users sign up on any website, a password is given in the raw form. But storing the raw passwords in the database directly is not a good practice. Using some server-side logic we first convert raw passwords in the (hashed+salt) form then store it in
5 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 modules for this purpose is bcryptjs. What is bcryptjs
3 min read
How to export promises from one module to another module node.js ?
JavaScript is an asynchronous single-threaded programming language. Asynchronous means multiple processes are handled at the same time. Callback functions vary for the asynchronous nature of the JavaScript language. A callback is a function that is called when a task is completed, thus helps in preventing any kind of blocking and a callback functio
1 min read
Angular PrimeNG Form Password Show Password Component
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will learn how to use the Password Show Password Component in Angular PrimeNG. The Password Component is used to represent the str
3 min read
Angular PrimeNG Form Password Password Meter Component
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will learn how to use the Password Password Meter Component in Angular PrimeNG. The Password Component is used to represent the st
3 min read
How to compare password and confirm password inputs using express-validator ?
Registration or Sign Up on any website always requires a confirmed password input and it must be the same as the password. It is basically to ensure that the user enters the password full of his senses and there is no conflict happening. This functionality can be implemented anywhere in our code like in the index file or route file but this comes u
4 min read