DEV Community

Cover image for Simplest way of Password Hashing with bcrypt by SilvenLEAF
SilvenLEAF
SilvenLEAF

Posted on • Edited on

Simplest way of Password Hashing with bcrypt by SilvenLEAF

We use bcrypt to hash our passwords. But how to use it? We generally do 2 basic things with bcrypt.

  • hash a password (I mean, when signing up, we hash the password input and then save this hashed password instead of the plain password on our database)

  • verify password (I mean, when logging in, compare the plain password input with the hashed password that we saved)

The SIMPLEST WAY TO USE BCRYPT

  • Hash a password
//it creates the hashed password. Save this hashedPassword on your DB
const hashedPassword = bcrypt.hashSync(yourPasswordFromSignupForm, bcrypt.genSaltSync());
Enter fullscreen mode Exit fullscreen mode

now save this hashedPassword on your Database.

  • Verify Password
const doesPasswordMatch = bcrypt.compareSync(yourPasswordFromLoginForm, yourHashedPassword)
Enter fullscreen mode Exit fullscreen mode

doesPasswordMatch is a bolean. If the passwords match, it'll be true, else false.

COMPLETE GUIDE FOR USING BCRYPT

First, type this on your terminal to install the bcryptjs package
npm install bcryptjs

Now we are ready to use it.

Step 0.

Create your user model. In this case we are going to keep it simple. our model will only have email and password fields.

Step 1 (USING BCRYPT TO SAVE HASHED PASSWORD ON DB FOR SIGN UP).

const router = require('express').Router();
const User = require('YOUR_USER_MODEL');


const bcrypt = require('bcryptjs')


router.post('/signup', async (req, res)=>{
  // these emailFromSignupForm and passwordFromSignupForm are coming from your frontend
  const { emailFromSignupForm, passwordFromSignupForm } = req.body;

 //creating a new user on our database
  const newUser = await User.create({
  email: emailFromSignupForm,
  hashedPassword: bcrypt.hashSync(passwordFromSignupForm, bcrypt.genSaltSync()),
});

//sending back the newUser to the frontEND
res.json(newUser);


})


module.exports = router;
Enter fullscreen mode Exit fullscreen mode

This is a demo code of how to use bcrypt to hash the password and save the hashed password.

Step 2 (USING BCRYPT TO COMPARE PASSWORDS FOR LOG IN).

const router = require('express').Router();
const User = require('YOUR_USER_MODEL');


const bcrypt = require('bcryptjs')


router.post('/login', async (req, res)=>{
  // these emailFromLoginForm and passwordFromLoginForm are coming from your frontend
  const { emailFromLoginpForm, passwordFromLoginForm } = req.body;

  //find a user from the database with your emailFromLoginForm
 const existingUser = await User.findOne({ email: emailFromLoginForm });

//if no user found
if(!existingUser) return res.json({ msg: `No account with this email found` })

//if the user is found, I mean if the user is on our database, compare the passwordFromLoginForm with the hashedPassword on our database to see if the passwords match (bcrypt will do this for us)
const doesPasswordMatch = bcrypt.compareSync(passwordFromLoginForm, existingUser.hashedPassword); //it wii give you a boolean, so the value of doesPasswordMatch will be a boolean

//if the passwords do not match
if(!doesPasswordMatch) return res.json({ msg: `Passwords did not match` });

//if the passwords match, send back the existingUser to the frontEND
res.json(existingUser);
}


})


module.exports = router;
Enter fullscreen mode Exit fullscreen mode

This is a demo code of how to use bcrypt to compare and verify passwordFromYourLoginForm with the hashedPassword saved on your Database.

This is ONLY a demo of how to use bcrypt. Hope it helps.

If you have any Questions or If you are stuck

Feel free to reach out to me. You can also contact me on LinkedIN https://www.linkedin.com/in/silvenleaf/ or on Twitter (as @silvenleaf ).

If you wanna know more about me, this is my portfolio website SilvenLEAF.github.io

I'd LOVE to be your friend, feel FREE to reach out to me!!

Next blog


FETCH API (easiest explanation)Part 1/4 (GET)(Series)

Next Blogs DATE

  • Nov 3rd, 4th, 5th 2020, FETCH API SERIES
  • Nov 6th 2020, async and await
  • Nov 8th 2020, how to use role-based auth system

  • Nov 10th 2020, Change CSS variables with JavaScript

  • Nov 12th, 14th, 16th 2020, Create login signup system with Passport (Series)

  • Nov 18th 2020, How to create Login with Google

  • Nov 20th 2020, How to create Login with Github

  • Nov 22th 2020, How to create Login with LinkedIn

  • Nov 24th 2020, How to create Login with Twitter

  • Nov 26th, 28th, 30th 2020, Password Reset Series (with Node.js and React)

If this blog was helpful to you,

PLEASE give a LIKE and share,

it'd mean a lot to me. Thanks

Top comments (0)