Skip to content

Instantly share code, notes, and snippets.

@pkyeck
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pkyeck/9047805 to your computer and use it in GitHub Desktop.
Save pkyeck/9047805 to your computer and use it in GitHub Desktop.
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