-
-
Save bitsmanent/b565eed443100f27b76c6c0980e03467 to your computer and use it in GitHub Desktop.
Hashing and verifying in Node.js using pbkdf2
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
const crypto = require("crypto"); | |
const config = { | |
hashBytes: 32, | |
saltBytes: 16, | |
iterations: 300000, | |
digest: "sha512" | |
}; | |
function hashPassword(pwd) { | |
const {saltBytes} = config; | |
const salt = crypto.randomBytes(saltBytes).toString("hex"); | |
const hash = makehash(pwd, salt); | |
return [salt, hash].join("$"); | |
} | |
function makehash(pwd, salt) { | |
const {iterations, hashBytes, digest} = config; | |
return crypto.pbkdf2Sync(pwd, salt, iterations, hashBytes, digest).toString("hex"); | |
} | |
function verifyPassword(pwd, combined) { | |
const [salt, originalHash] = combined.split("$"); | |
const hash = makehash(pwd, salt); | |
return hash === originalHash; | |
} | |
module.exports = {hashPassword,verifyPassword}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment