Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { randomBytes, pbkdf2Sync } = require("crypto");
- const argon2 = require("@node-rs/argon2");
- /**
- * Password hash utils
- * using MocoBaas logic and flow
- */
- const pwdHash = {
- hashPassword: (pwd) => {
- const salt = randomBytes(16).toString("hex");
- const hash = pbkdf2Sync(pwd, salt, 2048, 32, "sha512").toString("hex");
- return [salt, hash].join("$");
- },
- verifyPassword: (pwd, storedPwd) => {
- if (!storedPwd) return false;
- // if the hash started with $ sign, it's hash v2 (argon2id)
- // we need to remove base64 padding
- if (storedPwd.startsWith("$")) {
- // remove base64 padding from salt and hash
- // reference: https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md
- const fields = storedPwd.split("$");
- fields[4] = fields[4].replace(/=+$/, "");
- fields[5] = fields[5].replace(/=+$/, "");
- storedPwd = fields.join("$");
- return argon2.verifySync(storedPwd, pwd);
- }
- const [salt, originalHash] = storedPwd.split("$");
- const hash = pbkdf2Sync(pwd, salt, 2048, 32, "sha512").toString("hex");
- return hash === originalHash;
- },
- };
- module.exports = pwdHash;
Add Comment
Please, Sign In to add comment