Create a gist now

Instantly share code, notes, and snippets.

Storing and retrieving secure passwords
var crypto = require("crypto");
// user submitted form with email + pwd
var pwd = req.params.pwd;
// fetch result from DB ...
// retrieve hash from DB and compare to pwd
var result = <RESULT>;
var meta = fromStore.split(":");
var salt = new Buffer(meta[1], "base64");
var hash = meta[0];
// encrypt+salt password
var encrypted = crypto.pbkdf2(pwd, salt, 10000, 64, function(err, key) {
if (err) {
return reject(err);
}
key.toString("base64"));
});
// check if passwords match
if (hash !== encrypted) {
throw new Error("credentials unknown");
}
// user is logged in ...
var crypto = require("crypto");
var pwd = "topsecret";
// create random salt
var salt = crypto.randomBytes(64);
// encrypt+salt password
var encrypted = crypto.pbkdf2(pwd, salt, 10000, 64, function(err, key) {
if (err) {
return reject(err);
}
key.toString("base64"));
});
// combine hash + salt
var toBeStored = encrypted + ":" + salt.toString("base64");
// store in DB in one column ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment