Created
November 23, 2019 10:43
-
-
Save zazapeta/c383e02b9832bb9aa618f6b0dee071e4 to your computer and use it in GitHub Desktop.
Password hashing/verifying in node.js using 'pbkdf2'
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
const crypto = require("crypto"); | |
// larger numbers mean better security | |
const config = { | |
// size of the generated hash | |
hashBytes: 32, | |
// larger salt means hashed passwords are more resistant to rainbow table, but | |
// you get diminishing returns pretty fast | |
saltBytes: 16, | |
// more iterations means an attacker has to take longer to brute force an | |
// individual password, so larger is better. however, larger also means longer | |
// to hash the password. tune so that hashing the password takes about a | |
// second | |
iterations: 872791, | |
digest: "sha512" | |
}; | |
/** | |
@params {String} password - given password to hash | |
@returns {String} the hash corresponding to the password | |
*/ | |
function hashPassword(password) { | |
const { iterations, hashBytes, digest, saltBytes } = config; | |
const salt = crypto.randomBytes(saltBytes).toString("hex"); | |
const hash = crypto | |
.pbkdf2Sync(password, salt, iterations, hashBytes, digest) | |
.toString("hex"); | |
return [salt, hash].join("$"); | |
} | |
/** | |
@params {String} password - password to verify | |
@params {String} combined - a combined salt + hash returned by hashPassword function | |
@returns {Boolean} true if password correspond to the combined. False otherwise | |
*/ | |
function verifyPassword(password, combined) { | |
const { iterations, hashBytes, digest } = config; | |
const [salt, originalHash] = combined.split("$"); | |
const hash = crypto | |
.pbkdf2Sync(password, salt, iterations, hashBytes, digest) | |
.toString("hex"); | |
return hash === originalHash; | |
} | |
module.exports.verifyPassword = verifyPassword; | |
module.exports.hashPassword = hashPassword; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment