Created
February 21, 2014 13:27
-
-
Save sapher/9134180 to your computer and use it in GitHub Desktop.
Hashing password with NodeJS
This file contains hidden or 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
| crypto = require('crypto'); | |
| //Iterations | |
| iterations = 100; | |
| //Length | |
| length = 32; | |
| /* | |
| Generate the salt | |
| @params {function} cb - Callback that return the generated salt | |
| */ | |
| generateSalt = function(cb) { | |
| crypto.randomBytes(32, function(err, salt) { | |
| cb(err, salt.toString('base64')); | |
| }); | |
| }; | |
| /* | |
| Generate the hashed password | |
| @params {string} password - Password to hash | |
| @params {string} salt - Salt use to generated the hashed password | |
| @params {function} cb - Callback that return the generated hash | |
| */ | |
| generateHash = function(password, salt, cb) { | |
| crypto.pbkdf2(password, salt, iterations, length, function(err, hash) { | |
| cb(err, hash.toString('base64')); | |
| }); | |
| }; | |
| /* | |
| Check if a password is equal to a hashed one | |
| @params {string} password - plain text password | |
| @params {string} salt - salt used to generate the hashed password | |
| @params {string} hash - hashed password | |
| @params {function} cb - return a boolean if it's equal or not | |
| */ | |
| isEqual = function(password, salt, hash, cb) { | |
| crypto.pbkdf2(password, salt, iterations, length, function(err, nhash) { | |
| cb(err, (nhash.toString('base64') === hash) ? true : false); | |
| }); | |
| }; | |
| //TEST | |
| user = {}; | |
| //Generate the salt | |
| generateSalt(function(err, salt) { | |
| user.salt = salt; | |
| //Generate the password | |
| generateHash('secret', salt, function(err, hash) { | |
| user.password = hash; | |
| //Test if the hashed password is equal to the plain text one | |
| isEqual('secret', salt, hash, function(err, equal) { | |
| if(equal) console.log('valid'); | |
| else console.log('not valid'); //not valid of course | |
| console.log(user); //store this object somewhere warm | |
| }); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment