Hashing passwords with Bcrypt and node.js
I have a little pet project that I'm using to learn Hapi.js.
Today I wanted to add authentication and since this is, as I said, a tiny little mini project, I want to only allow specific users (actually, just me) to log in, and not everyone+dog using bell or something of that sort. So I thought I'd go for hapi-auth-basic.
This module performs, not surprisingly, an HTTP basic authentication, and also wants a password hash generated with Bcrypt. I didn't really find a command line thing that would generate the hash for me on this mac computer in a convenient fuss free way, and I also didn't really spend hours looking because it's Saturday, so in my most pragmatic move of today I decided I would just write a little snippet of code that would hash and verify the password using JavaScript.
So here it is, roughly based off this post of using Bcrypt with mongoose.
var Bcrypt = require('bcrypt');
var SALT_WORK_FACTOR = 10;
var pass = '123456789';
Bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if(err) {
return console.error(err);
}
Bcrypt.hash(pass, salt, function(err, hash) {
if(err) {
return console.error(err);
}
console.log(hash);
Bcrypt.compare(pass, hash, function(err, isMatch) {
if(err) {
return console.error(err);
}
console.log('do they match?', isMatch);
});
});
});
The output could be, for example:
$2a$10$ezsikcAtcBL6SZQNoZJ2..v7xaxyYXEkRmAyN9FqDJySXE4NWDk.O
do they match? true```
Then when you create the object with users that hapi-auth-basic uses, you create the hash for each users' password using that sequence of <tt>Bcrypt.genSalt</tt> and <tt>Bcrypt.hash</tt>.
I am not totally sure this is perfectly fine, so if any node+encryption expert wants to correct me, feel free to add a comment! Thanks :-)