Open In App

Node.js crypto.pbkdf2Sync() Method

Last Updated : 23 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The crypto.pbkdf2Sync() method gives a synchronous 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.pbkdf2Sync( password, salt, iterations, keylen, digest )

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

  • password: It is of type string, Buffer, TypedArray, or DataView.
  • salt: It must be as unique as possible. However, it is recommended that a salt is arbitrary and in any case, it is at least 16 bytes long. It is of type string, Buffer, TypedArray, or DataView.
  • iterations: It must be a number and should be set as high as possible. So, the more is the number of iterations, the more secure the derived key will be, but in that case, it takes a greater amount of time to complete. It is of type number.
  • keylen: It is the key of the required byte length and it is of type number.
  • digest: It is a digest algorithm of string type.

Return Type: It returns the derived key as buffer. The below examples illustrate the use of crypto.pbkdf2Sync() method in Node.js: 

Example 1: 

javascript




// Node.js program to demonstrate the
// crypto.pbkdf2Sync() method
 
// Including crypto module
const crypto = require('crypto');
 
// Implementing pbkdf2Sync
const key = crypto.pbkdf2Sync('secret',
           'salt', 2000, 64, 'sha512');
 
// Prints buffer
console.log(key);


Output:

<Buffer 3c f1 85 49 62 52 38 64 2a 4e b1 4c f6 25 2e 1e fc
d7 8e 01 c9 40 d7 84 63 5e 24 ef 71 0f 91 83 bb 6d 03 bd
73 43 33 ec 78 a9 78 c8 1f ea7a dc 8c a6 ...>

Example 2: 

javascript




// Node.js program to demonstrate the
// crypto.pbkdf2Sync() method
 
// Including crypto module
const crypto = require('crypto');
 
// Implementing pbkdf2Sync
const key = crypto.pbkdf2Sync('secret',
       'salt', 100000, 100, 'sha512');
 
// Prints key which is encoded and converted
// to string
console.log(key.toString('hex'));


Output:

3745e482c6e0ade35da10139e797157f4a5da669dad7d5da88ef87e4
7471cc47ed941c7ad618e827304f083f8707f12b7cfdd5f489b782f10cc269
e3c08d59ae04919ee902c99dba309cde75569fbe8e6d5c341d6f2576f6618c
589e77911a261ee964e2

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads