Skip to content

Instantly share code, notes, and snippets.

@vivekyadav5750
Last active January 23, 2024 05:42
Show Gist options
  • Save vivekyadav5750/28a5c9ebe7a73f50c8fd1bfebc734aa4 to your computer and use it in GitHub Desktop.
Save vivekyadav5750/28a5c9ebe7a73f50c8fd1bfebc734aa4 to your computer and use it in GitHub Desktop.
Nodejs Hashing

Hashing Passwords with bcrypt (module) in JavaScript

In this example, we use the bcrypt module to hash and compare passwords securely. This can be useful for password storage in databases.

Dependencies

Ensure you have the bcrypt module installed:

npm install bcrypt

Code Implementation

// Import necessary modules
import bcrypt from "bcrypt";
import { customErrorHandler } from "../middlewares/errorHandler.js";

// Hashing function
export const hashPassword = async (password, next) => {
    try {
        // Hash the password with a salt factor of 12
        return await bcrypt.hash(password, 12);
    } catch (error) {
        // Handle errors during hashing
        next(new customErrorHandler(400, "Encountered an error in hashing password"));
    }
};

// Password comparison function
export const compareHashedPassword = async (password, hashPassword, next) => {
    try {
        // Compare the input password with the hashed password
        return await bcrypt.compare(password, hashPassword);
    } catch (error) {
        // Handle errors during password comparison
        next(new customErrorHandler(400, "Encountered an error in comparing hashed password"));
    }
};

Usage

  1. Hashing a Password:
const hashedPassword = await hashPassword("user_password", next);
// 'hashedPassword' now contains the securely hashed password.
  1. Comparing Passwords:
const isMatch = await compareHashedPassword("user_input_password", hashedPassword, next);
// 'isMatch' will be true if the passwords match, otherwise false.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment