DEV Community

Arbaoui Mehdi
Arbaoui Mehdi

Posted on

Use bcrypt to campare passwords using nodejs

Storing your password as a plain text is fast, however it is not secure, this why you have to make it complicated for hackers to get important information by using hashing, there is a couple of hashing functions like md5, we’ll not use md5 which it is not designed for passwords plus it’s cryptographically broken when the attacker can generate a list of common password and their corresponding hashes, then comparing the hashes to the site has stored.

You’ll use bcrypt which it is more designed for passwords, bcrypt use a salt to make a hash output unique even if your users use the same password, and this is a simple use case of bcrypt for a user who wanna update his password.

const bcrypt = require("bcryptjs");

// Generate Salt
const salt = bcrypt.genSaltSync(10);

// Plain Text Passwords
const currentpPassword = "abc123";
const oldPassword = "abc123";
const newPassword = "nWd6yCyj";

// Generate the Current User Password Hash
// by combining the salt and the password
const currentPasswordHash = bcrypt.hashSync(currentpPassword, salt);

// Compare the Old Password set by the user
// to the Current Password Hash
if (!bcrypt.compareSync(oldPassword, currentPasswordHash)) {
  console.log("The Current Password is Wrong");
}

// The new password should not be similar
// to the old password
if (bcrypt.compareSync(newPassword, currentPasswordHash)) {
  console.log(
    "The new password is similar to the new password, please choose a different one",
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)