How to use the pbkdf2 function from crypto

Find comprehensive JavaScript crypto.pbkdf2 code examples handpicked from public code repositorys.

crypto.pbkdf2 is a Node.js method that creates a key derivation object using a password, a salt, and an iteration count, in order to generate a secure hash.

29
30
31
32
33
34
35
36
37
38
passport.use(new LocalStrategy(function verify(username, password, cb) {
  db.get('SELECT * FROM users WHERE username = ?', [ username ], function(err, user) {
    if (err) { return cb(err); }
    if (!user) { return cb(null, false, { message: 'Incorrect username or password.' }); }
    
    crypto.pbkdf2(password, user.salt, 310000, 32, 'sha256', function(err, hashedPassword) {
      if (err) { return cb(err); }
      if (!crypto.timingSafeEqual(user.hashed_password, hashedPassword)) {
        return cb(null, false, { message: 'Incorrect username or password.' });
      }
fork icon66
star icon44
watch icon6

287
288
289
290
291
292
293
294
295

if(typeof cachedDerivedKeys[cacheKey] !== "undefined"){
    return resolve(cachedDerivedKeys[cacheKey])
}

crypto.pbkdf2(password, salt, iterations, bitLength, hash, (err, res) => {
    if(err){
        return reject(err)
    }
fork icon24
star icon118
watch icon8

How does crypto.pbkdf2 work?

crypto.pbkdf2() is a method in Node.js's built-in crypto module that generates a derived cryptographic key from the provided password and salt values, using a specified number of iterations and a hash algorithm, such as SHA1 or SHA256.

The derived key can then be used for secure cryptographic operations such as encryption and decryption.

143
144
145
146
147
148
149
150
151
152
const ip = createHash('sha256').update((req.headers['x-forwarded-for'] || req.socket.remoteAddress)).digest('hex');;
if (req.body["type"] === "login") {
    const user = await mongoClient.collection('Users').findOne({email: {$eq: req.body["data"]["email"]}});
    if (user === null) return res.status(200).json({status: 401, accepted: false, message: "Invalid Credentials" });
    else if (user["email"] === req.body["data"]["email"]) {
        pbkdf2(req.body["data"]["pswd"], user["pswd"]["salt"], 1000000, 32, 'sha256', async (err, derivedKey) => {
            if (timingSafeEqual(Buffer.from(user["pswd"]["hash"], 'hex'), derivedKey)) {
                let session = await mongoClient.collection('Sessions').findOne({userDocumentID: {$eq: user._id}, userAgent: {$eq: req.get('User-Agent')}, ip: {$eq: ip}});
                if (session === null) {
                    const token = await createHash('sha256').update(user._id.id.toString('hex') + uuidv4() + ip).digest('hex');
fork icon0
star icon1
watch icon0

207
208
209
210
211
212
213
214
215
216
if (err) {
    console.log(err)
    return response(req, res, -200, "서버 에러 발생", [])
} else {
    if (result1.length > 0) {
        await crypto.pbkdf2(pw, salt, saltRounds, pwBytes, 'sha512', async (err, decoded) => {
            // bcrypt.hash(pw, salt, async (err, hash) => {
            let hash = decoded.toString('base64');
            console.log(hash)
            console.log(result1[0].pw)
fork icon0
star icon0
watch icon1

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const crypto = require("crypto");

const password = "myPassword";
const salt = crypto.randomBytes(16);
const iterationCount = 10000;
const keyLength = 64;

crypto.pbkdf2(
  password,
  salt,
  iterationCount,
  keyLength,
  "sha512",
  (err, derivedKey) => {
    if (err) throw err;
    console.log(derivedKey.toString("hex"));
  }
);

In this example, the function generates a derived key using the password string, a randomly generated salt, 10000 iterations of the hash function, a key length of 64 bytes, and the SHA-512 hash algorithm. The derived key is then printed to the console in hexadecimal format.

230
231
232
233
234
235
236
237
238
239
for (let i = 0; i < users.length; i++) {  
  let countDuplicateUsers = await MongoDatabase.db("Authentication").collection("Credentials").countDocuments({username:users[i].username});
  if (countDuplicateUsers==0) {
    if (users[i].password) {
      let salt = JSON.stringify(crypto.randomBytes(16).toJSON().data);
      crypto.pbkdf2(users[i].password, Buffer.from(salt.toString()), 310000, 32, 'sha256', async function(err, hashedPassword) {
      await MongoDatabase.db("Authentication").collection("Credentials").updateOne({username: users[i].oldUsername}
        , {
            $set: {
              "username": users[i].username,
fork icon0
star icon0
watch icon1

+ 3 other calls in file

361
362
363
364
365
366
367
368
369
370
if (!row) {
  return cb(null, false, {
    message: "Incorrect username or password.",
  });
}
crypto.pbkdf2(
  password,
  row.Salt,
  2023,
  32,
fork icon0
star icon0
watch icon1

20
21
22
23
24
25
26
27
28
29
}
userService.getOne(email).then((data) => {
    if(data === null) {
        return res.jsend.fail({"result": "Incorrect email or password"});
    }
    crypto.pbkdf2(password, data.salt, 310000, 32, 'sha256', function(err, hashedPassword) {
      if (err) { return cb(err); }
      if (!crypto.timingSafeEqual(data.encryptedPassword, hashedPassword)) {
          return res.jsend.fail({"result": "Incorrect email or password"});
      }
fork icon0
star icon0
watch icon0

+ 5 other calls in file

691
692
693
694
695
696
697
698
699
700
701
702
703
  assert.strictEqual(actual, expected);


  const cb = common.mustCall((err, actual) => {
    assert.strictEqual(actual, expected);
  });
  crypto.pbkdf2(password, salt, iterations, keylen, 'sha256', cb);
}




testPBKDF2('password', 'salt', 1, 20,
fork icon0
star icon0
watch icon0

36
37
38
39
40
41
42
43
44
45
46
47


d.run(function() {
  one();


  function one() {
    crypto.pbkdf2('a', 'b', 1, 8, 'sha1', function() {
      two();
      throw new Error('pbkdf2');
    });
  }
fork icon0
star icon0
watch icon0

39
40
41
42
43
44
45
46
47
48
if(data === null) {
    return res.jsend.fail({"result": "Incorrect email or password"});
}

// Verify password using PBKDF2
crypto.pbkdf2(password, data.Salt, 310000, 32, 'sha256', function(err, hashedPassword) {
    if (err) { return cb(err); }

    // If password doesn't match, return error
    if (!crypto.timingSafeEqual(data.EncryptedPassword, hashedPassword)) {
fork icon0
star icon0
watch icon0

+ 5 other calls in file

12
13
14
15
16
17
18
19
20
21
22
23
    callback = digest
    digest = 'sha1'
  }
  if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')


  return native.pbkdf2(password, salt, iterations, keylen, digest, callback)
}


function nativePBKDF2Sync (password, salt, iterations, keylen, digest) {
  checkParameters(iterations, keylen)
fork icon0
star icon0
watch icon0