DEV Community

Carlos Guzmán
Carlos Guzmán

Posted on

How to hash a password before save into DB with JavaScript and bcrypt.

When you save data from users, such as username, email, phone numbers, and other data, is usually save these data in plain text, however, for user passwords, it is not secure, because, if your DB is compromised, all passwords its exposes.

So, hash all password before save into DB, usually is a good practice. bcrypt, is a JavaScript Library for this propose.

Remember init your npm project with npm init and install the library with npm install bcrypt.

Now implement your library.

const bcrypt = require('bcrypt'); // import the Library. 
const saltRounds = 10; // The number of rounds for encrypt the passwords. 
const myPlaintextPassword = 'examplePassword';

// Now, use bcrypt for encrypt the plain Password. 

bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
    // Store hash in your password DB.
    console.log(hash); 
});

Enter fullscreen mode Exit fullscreen mode

If you need compare un plain Password with your saved password, you can use the function compare.

bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
    // result == true
if(result==true){
 // The Password is Correct!
}
else {
 // Your password is not correct. 
}
});

Enter fullscreen mode Exit fullscreen mode

It's All,

Thanks!

Latest comments (0)