-
-
Save brandonsueur/d441aeea512c6fb1b536f2bd29e2c23d to your computer and use it in GitHub Desktop.
Using bcrypt with promises to hash a password and then verify it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let bcrypt = require('bcrypt-nodejs'); | |
let password = "hello"; | |
let stored_hash = ""; | |
// first generate a random salt | |
function genSalt(password) { | |
return new Promise((resolve,reject) => { | |
bcrypt.genSalt(10,function(err,salt) { | |
if (err) { | |
reject(err); | |
} | |
else { | |
resolve({ | |
salt:salt, | |
password:password | |
}); | |
} | |
}); | |
}); | |
} | |
// hash the password with the salt | |
function genHash(salt,password) { | |
return new Promise((resolve,reject) => { | |
bcrypt.hash(password,salt,null,function(err,hash) { | |
if (err) { | |
reject(err); | |
} | |
else { | |
resolve({ | |
salt:salt, | |
password:password, | |
hash:hash | |
}); | |
} | |
}); | |
}); | |
} | |
// execute in sequence | |
console.log("store"); | |
genSalt(password) | |
.then(function(result) { | |
return genHash(result.salt,result.password); | |
}) | |
.then(function(result) { | |
console.log('store hash in user profile :', result); | |
stored_hash = result.hash; | |
}) | |
.catch(function(err) { | |
console.log(err); | |
}); | |
// ===================================================== | |
function lookupUser(user,passwd) { | |
return new Promise((resolve,reject) => { | |
// lookup the user in the stored database | |
// in this case its not async so just resolve with the stored hash | |
resolve({ | |
user:user, | |
password:passwd, | |
hash1:stored_hash | |
}) | |
}) | |
} | |
function reHash(user,password,hash1) { | |
let salt = hash1.substr(0,30); | |
return new Promise((resolve,reject) => { | |
bcrypt.hash(password,salt,null,function(err,hash2) { | |
if (err) { | |
reject(err); | |
} | |
else { | |
resolve({ | |
user:user, | |
salt:salt, | |
password:password, | |
hash1:hash1, // stored hash | |
hash2:hash2 // generated hash | |
}); | |
} | |
}); | |
}); | |
} | |
// lookup and verify | |
setTimeout(function() { | |
console.log("verify"); | |
lookupUser("joe",password) | |
.then(function(result) { | |
return reHash(result.user,result.password,result.hash1); | |
}) | |
.then(function(result) { | |
console.log(result.hash1); | |
console.log(result.hash2); | |
if (result.hash1 === result.hash2) { | |
console.log('verified'); | |
} | |
else { | |
console.log('failed'); | |
} | |
}) | |
.catch(function(err) { | |
console.log(err); | |
}); | |
},1000); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment