crypto.pbkdf2Sync() Method in Node.js

Node.jsJavascriptWeb DevelopmentFront End Technology

The crypto.pbkdf2Sync(), also known as Password-Based Key Derivation function 2, provides a synchronous implementation of the derivative function. A key is derived by using the Hmac digest of a specified algorithm from password, salt and iterations. This will create the key in a sync process.

Syntax

crypto.createHmac(algorithm, key, [options])

Parameters

The above parameters are described as below −

  • password – Password defined for getting key of the requested byte length. Possible values are of type string, DataView, Buffer, etc.

  • salt – Similar to password for getting the key. Possible values are of type string, DataView, Buffer, etc.

  • iterations – Getting the desired key of requested byte length. It accepts the value as number.

  • keylen – This is the requested byte length of the key. It is of type number.

  • digest – The Hmac algorithm is specified by this digest value. Default value is 'sha1'

Example

Create a file with name – pbkdf2Sync.js and copy the below code snippet. After creating file,use the following command to run this code as shown in the example below −

node pbkdf2Sync.js

pbkdf2Sync.js

 Live Demo

// crypto.pbkdf2() demo example

// Importing the crypto module
const crypto = require('crypto');

// Defining the pbkdf2 with the following options
const pbkdfKey = crypto.pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
// Printing the derivedKey
console.log("key is: ",pbkdfKey.toString('hex'));

Output

C:\home\node>> node pbkdf2Sync.js
key is:
3745e482c6e0ade35da10139e797157f4a5da669dad7d5da88ef87e47471cc47ed941c7ad618e8
27304f083f8707f12b7cfdd5f489b782f10cc269e3c08d59ae

Example

Let's take a look at one more example.

 Live Demo

// crypto.pbkdf2Sync () demo example

// Importing the crypto module
const crypto = require('crypto');

// Defining the pbkdf2Sync with the following options
const pbkdfKey = crypto.pbkdf2Sync('secret', 'salt', 100, 32, 'sha1');
// Printing the derivedKey
console.log("key is: ",pbkdfKey);
console.log("key(in hex) is: ",pbkdfKey.toString('hex'));
console.log("key(in base64) is: ",pbkdfKey.toString('base64'));

Output

C:\home\node>> node pbkdf2Sync.js
key is: <Buffer b7 36 35 f7 c0 88 2e 1f c3 ba 6e 29 b1 4a f1 27 4d f8 48 28
b4 d1 8f cc 22 2e b5 74 45 5f 50 5d>
key(in hex) is:
b73635f7c0882e1fc3ba6e29b14af1274df84828b4d18fcc222eb574455f505d
key(in base64) is: tzY198CILh/Dum4psUrxJ034SCi00Y/Mii61dEVfUF0=
raja
Published on 20-May-2021 11:57:14
Advertisements