node.js securing the username/password database

Following on from my last post, I decided to have a look at a better solution for password hashing as the last example just used SHA1 which is far from optimal, so here are some changes to handle hashing via a pbkdf2 function which is far far better and far more secure.

The passport auth function now looking like

passport.use(new LocalStrategy(function(username, password,done){
    Users.findOne({ username : username},function(err,user){
        if(err) { return done(err); }
            return done(null, false, { message: 'Incorrect username.' });
	var iterations = 2500;
	var keylen = 512;
	var salt = user.salt;
	var hash=new Buffer(crypto.pbkdf2Sync(password,salt, iterations, keylen), 'binary').toString('base64');

        if (hash == user.password) 
        	return done(null, user._id);
            done(null, false, { message: 'Incorrect password.' });

and this requires we have the following fields in the database (report) username,password and salt.

To add a new user to the database you could use a route as follows which accepts a post request :-

exports.adduser2 = function(db,crypto) {
    return function(req, res) {
      var collection = db.get('users');
      var password= req.body.password;
      var username = req.body.username;
      var iterations = 2500;
      var keylen = 512;
      var salt = new Buffer(crypto.randomBytes(512)).toString('hex');
      var hash=new Buffer(crypto.pbkdf2Sync(password,salt, iterations, keylen), 'binary').toString('base64')

            	"username" : username,
            	"password" : hash,
            	"salt" : salt,

The number of iterations and key length and salt length can all be changed to increase difficulty but I belive thats pretty darn difficult with those options, but do ensure you use the same settings for key length and iterations for the adduser and the password checking functions!

Leave a Reply