Skip to content

Instantly share code, notes, and snippets.

@geek0x23
Last active December 13, 2015 18:38
Show Gist options
  • Save geek0x23/4956571 to your computer and use it in GitHub Desktop.
Save geek0x23/4956571 to your computer and use it in GitHub Desktop.
A simple async PBKDF2 hashing library which I wrote based on the ideas behind StackOverflow's implementation. I haven't had the chance to test it yet, but it should be pretty close :)
"use strict";
var crypto = require("crypto"),
saltSize = 16,
hashIterations = 5000;
function generateSalt(iterations, cb) {
if (iterations === undefined) { iterations = hashIterations; }
if (iterations < hashIterations) { throw new Error("iterations cannot be less than " + hashIterations); }
var bytes = crypto.randomBytes(saltSize, function(err, buff) {
if (err) { cb(err, null); }
cb(null, iterations.toString(16) + "." + buff.toString("base64"));
});
}
function hash(password, salt, cb) {
var i = salt.indexOf(".");
var iters = parseInt(salt.substring(0, i), 16);
salt = salt.substring(i + 1);
crypto.pbkdf2(password, salt, iters, 64, function(err, derivedKey) {
if (err) { cb(err, null); }
if (typeof derivedKey === 'string') {
derivedKey = new Buffer(derivedKey, "binary");
}
cb(null, derivedKey.toString("base64"));
});
}
module.exports = {
generatePasswordHash: function(password, cb) {
generateSalt(hashIterations, function(err, salt) {
if (err) { cb(err, null); }
hash(password, salt, function(err, result) {
if (err) { cb(err, null); }
cb(null, "$" + salt + "$" + result);
});
});
},
validatePasswordHash: function(password, hashed, cb) {
var secondDollar = hashed.indexOf("$", 1);
var salt = hashed.substring(1, secondDollar);
hash(password, salt, function(err, result) {
if (err) { cb(err, null); }
cb(null, result === hashed.substring(secondDollar + 1));
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment