Last Updated: February 25, 2016
·
3.403K
· sschepis

Node.js - Create strong password hashes with this function

Hashing your user passwords before committing them to persistent storage is a must in any environment where security is important. Node.js makes this easy to do with its built-in crypto library. Here's a node.js function I use to generate strong password hashes using node.js' crypto.pbkdf2 functionality:

// generate a strong password hash (make sure you choose a salt
// or capture the salt randomly generated for you!)
var hashPassword = function (opts, callback) {
    // make sure some plaintext is present 
    // if not make some up and call this method recursively
    if (!opts.plaintext) {
        return crypto.randomBytes(6, function (err, buf) {
            if (err) callback(err);
            opts.plaintext = buf.toString('base64');
            return hashPassword(opts, callback);
        })
    }
    // make sure a salt is present in input
    // if not make a salt up
    if (!opts.salt) {
        return crypto.randomBytes(64, function (err, buf) {
            if (err) return callback(err);
            opts.salt = buf;
            return hashPassword(opts, callback);
        })
    }
    // we use pbkdf2 to hash and iterate 10k times by default 
    // hashed password is in opts.key in the callback
    opts.hash = 'sha1';
    opts.iterations = opts.iterations || 10000;
    return crypto.pbkdf2(opts.plaintext, opts.salt, opts.iterations, 64, function (err, key) {
        if (err) return callback(err);
        opts.key = new Buffer(key);
        return callback(null, opts);
    })
};

1 Response
Add your response

Good !
It helped me, thanks a lot.

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside