BayangBec

Untitled

Oct 3rd, 2023
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const { randomBytes, pbkdf2Sync } = require("crypto");
  2. const argon2 = require("@node-rs/argon2");
  3. /**
  4.  * Password hash utils
  5.  * using MocoBaas logic and flow
  6.  */
  7. const pwdHash = {
  8.   hashPassword: (pwd) => {
  9.     const salt = randomBytes(16).toString("hex");
  10.     const hash = pbkdf2Sync(pwd, salt, 2048, 32, "sha512").toString("hex");
  11.  
  12.     return [salt, hash].join("$");
  13.   },
  14.  
  15.   verifyPassword: (pwd, storedPwd) => {
  16.     if (!storedPwd) return false;
  17.  
  18.     // if the hash started with $ sign, it's hash v2 (argon2id)
  19.     // we need to remove base64 padding
  20.     if (storedPwd.startsWith("$")) {
  21.       // remove base64 padding from salt and hash
  22.       // reference: https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md
  23.       const fields = storedPwd.split("$");
  24.       fields[4] = fields[4].replace(/=+$/, "");
  25.       fields[5] = fields[5].replace(/=+$/, "");
  26.       storedPwd = fields.join("$");
  27.  
  28.       return argon2.verifySync(storedPwd, pwd);
  29.     }
  30.  
  31.     const [salt, originalHash] = storedPwd.split("$");
  32.     const hash = pbkdf2Sync(pwd, salt, 2048, 32, "sha512").toString("hex");
  33.  
  34.     return hash === originalHash;
  35.   },
  36. };
  37.  
  38. module.exports = pwdHash;
  39.  
Add Comment
Please, Sign In to add comment