Search code examples
node.jsnode-crypto

SALT and HASH password in nodejs w/ crypto


I am trying to figure out how to salt and hash a password in nodejs using the crypto module. I am able to create the hashed password doing this:

UserSchema.pre('save', function(next) {
  var user = this;

  var salt = crypto.randomBytes(128).toString('base64');
  crypto.pbkdf2(user.password, salt, 10000, 512, function(err, derivedKey) {
    user.password = derivedKey;
    next();
  });
});

However I am confused about how to later validate the password.

UserSchema.methods.validPassword = function(password) {    
  // need to salt and hash this password I think to compare
  // how to I get the salt?
}

Solution

  • In whatever persistence mechanism (database) you're using, you would store the resulting hash alongside the salt and number of iterations, both of which would be plaintext. If each password uses different salt (which you should do), you must also save that information.

    You would then compare the new plain text password, hash that using the same salt (and iterations), then compare the byte sequence with the stored one.

    To generate the password (pseudo)

    function hashPassword(password) {
        var salt = crypto.randomBytes(128).toString('base64');
        var iterations = 10000;
        var hash = pbkdf2(password, salt, iterations);
    
        return {
            salt: salt,
            hash: hash,
            iterations: iterations
        };
    }
    

    To validate password (pseudo)

    function isPasswordCorrect(savedHash, savedSalt, savedIterations, passwordAttempt) {
        return savedHash == pbkdf2(passwordAttempt, savedSalt, savedIterations);
    }