Skip to content

Instantly share code, notes, and snippets.

@bitsmanent
Forked from zazapeta/auth.js
Last active May 2, 2024 20:20
Show Gist options
  • Save bitsmanent/b565eed443100f27b76c6c0980e03467 to your computer and use it in GitHub Desktop.
Save bitsmanent/b565eed443100f27b76c6c0980e03467 to your computer and use it in GitHub Desktop.
Hashing and verifying in Node.js using pbkdf2
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