How to encrypt and decrypt Password in NodeJS using bycryptJS

Encryption in the basic language is termed as transforming one simple word or sentence into a complex word that is not easily understandable. Let’s see How to encrypt and decrypt passwords in NodeJS.

This is done with some basic rule and the rule is used to again decrypt that complex word into simple.
Encryption is specially used to save passwords, account numbers, transaction ids that are not to be showcased or exposed on a public platform and are still used by end-user.

Encryption and decryption in nodeJS

There are several ways to encrypt and decrypt. NodeJS has a library named bycryptjs that is used to encrypt and decrypt using some algorithms. This is very useful to store passwords and important credentials in the database as even the owner of the site cannot access the password or sensitive data.

How to encrypt and decrypt Password in NodeJS

This protects the privacy of clients and gives freedom to use the site for transactions and other purposes. in the below example let’s create a simple NodeJS application to Encrypt and Decrypt Username and Password for the login form.

1. Install the package using the node package manager

npm install bycryptjs

2. Import the package inside the file where its goanna is used.

const bcrypt = require('bcryptjs');

3. Pass the argument that it will be encrypted and the second argument is number which indicates how strong password encryption should be using bycrypt.hash(word,number).

bcrypt.hash(password,10)
       .then(hashedpassword => {
           const user = new User({
               name,
               email,
               password:hashedpassword
           })
           user.save()
           .then(user=>{
               res.json({message:"Saved Succcessfully"})
           }).catch(err=>{
               console.log(err);
           })

4. For comparing the encrypted data we use a function called bycrypt.compare(word1,word2) this will return a true or false value if the decrypted term match.

bcrypt.compare(password,savedUser.password)
        .then(doMatch=>{
            if(doMatch){
                // res.json({message:"SignIn successfull"})
                const token = jwt.sign({_id:savedUser._id},JWT_SECRET)
                const {_id,name,email,role} = savedUser
                res.json({token,user:{_id,email,name,role}})
            }else{
                return res.status(422).json({error:"Invalid Email or Password"})
            }

Code Auth.js

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const {JWT_SECRET} = require('../keys');
const User = mongoose.model("User");
const {requireLogin,isAdmin} = require('../middleware/authmiddleware')

// SignUp       post      /auth/signup

router.post("/signup",(req,res)=>{
    const {email,name,password} = req.body
    if(!email || !password || !name){
        return res.status(422).json({error:"Please add all fields"});
    }
    User.findOne({email})
    .then((savedUser)=>{
        if(savedUser){
            return res.status(422).json({error:"User already exsist"})
        }
        bcrypt.hash(password,10)
        .then(hashedpassword => {
            const user = new User({
                name,
                email,
                password:hashedpassword
            })
            user.save()
            .then(user=>{
                res.json({message:"Saved Succcessfully"})
            }).catch(err=>{
                console.log(err);
            })
        })
      
    })
    
})

// SignIn       post      /auth/signin


router.post('/signin',(req,res)=>{
    const {email,password} = req.body;
    if(!email || !password){
        return res.status(422).json({error:"Please Add Email or Password"})
    }
    User.findOne({email})
    .then(savedUser => {
        if(!savedUser){
            return res.status(422).json({error:"Invalid email or password"})
        }
        bcrypt.compare(password,savedUser.password)
        .then(doMatch=>{
            if(doMatch){
                // res.json({message:"SignIn successfull"})
                const token = jwt.sign({_id:savedUser._id},JWT_SECRET)
                const {_id,name,email,role} = savedUser
                res.json({token,user:{_id,email,name,role}})
            }else{
                return res.status(422).json({error:"Invalid Email or Password"})
            }
        }).catch(err=>{
            console.log(err);
        })
    }).
    catch(err=>{
        console.log(err);
    })
})



module.exports = router

Here in the given example, we have used a simple password entered by the user but after encryption, we store it in the database. The password becomes very complex and even database admin cannot use it.

output

After Encryption