Languages

Node.js - why bcrypt generate different outputs for same input

3 points
Asked by:
Kia-H
546

I'm using bcrypt module to hash users' passwords in my database,  but I'm confused because for the same input I get different outputs.

Could someone explain, why bcrypt behaves like this?

1 answer
0 points
Answered by:
Kia-H
546

Without going into details of the implementation of the hashing algorithm, bcrypt returns a different value on the output each time, which depends on the random value of the 'salt' (saltRounds).
This makes it much more difficult to crack the encrypted password.

Check out the example below

const bcrypt = require('bcrypt');

const saltRounds = 10;
const password = '123456';

for (let i = 0; i < 5; i++) {
    let hashedPassword;

    bcrypt.hash(password, saltRounds, (error, hash) => { // encoding password 
        if (error) console.log(error);
        console.log(hash);
        hashedPassword = hash;

        bcrypt.compare(password, hashedPassword, (error, result) => { 
            if (error) console.log(error);
            console.log(result);  // result is true when password and hashedPassword match
        });
    });
}

Output: 

$2b$10$PceRYeIxAc6SsVxaCWf0wuIslXEOk9jdAbvYhtg2TqeZOfUa4BHn6
true
$2b$10$3QZrVO.2HNB6t70d9yBVsu8AYfVe5Ky.7PYemFP785M6PvF.a6u4.
true
$2b$10$b.661cpGPdptbWlJD/wiXuIOtHRt/nbkGJS/1qr/r5eUxoovd9/8.
true
$2b$10$gOancHkngDJvrXkW8O980Oozp9EnV8met6K11D2jDktGktROqwcoC
true
$2b$10$cNoPEzoNdy5aIZ59xAJPTu0fq.C1.4zjVRrgWzD8oEMj82lkVqZGq

After output, we can see that the encrypted password is different each time, but the result of each comparison is true.

You can also check this article:
Node.js - hash passwords using bcrypt

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join