Open In App

Node.js crypto.pbkdf2() Method

The crypto.pbkdf2() method gives an asynchronous Password-Based Key Derivation Function 2 i.e. (PBKDF2) implementation. Moreover, a particular HMAC digest algorithm which is defined by digest is implemented to derive a key of the required byte length (keylen) from the stated password, salt, and iterations.

Syntax:



crypto.pbkdf2( password, salt, iterations, keylen, digest, callback )

Parameters: This method accepts six parameters as mentioned above and described below:

Return Type: It returns the derived password based key.



Below example illustrate the use of crypto.pbkdf2() method in Node.js:

Example 1:




// Node.js program to demonstrate the 
// crypto.pbkdf2() method
  
// Including crypto module
const crypto = require('crypto');
  
// Implementing pbkdf2 with all its parameters
crypto.pbkdf2('secret', 'salt', 100000, 64,
         'sha512', (err, derivedKey) => {
  
  if (err) throw err;
  
  // Prints derivedKey
  console.log(derivedKey.toString('hex'));
});

Output:

3745e482c6e0ade35da10139e797157f4a5da669dad7d5da88ef87e
47471cc47ed941c7ad618e827304f083f8707f12b7cfdd5f489b782
f10cc269e3c08d59ae

Example 2:




// Node.js program to demonstrate the 
// crypto.pbkdf2() method
  
// Including crypto module
const crypto = require('crypto');
  
// Implementing pbkdf2 with all its parameters
// but digest is null
crypto.pbkdf2('secret', 'salt', 677, 6,
          null, (err, derivedKey) => {
  
  if (err) 
  {
    console.log(err);
  
  else
  {
  
  // Prints derivedKey without encoding
  console.log(derivedKey);
      
     }
});    

Output: Here, a buffer is returned as a derived key is not changed to string.

Buffer 71 1e 7b 7b 9b 53

Reference: https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback


Article Tags :