Skip to content
Related Articles

Related Articles

Node.js scrypto.hkdf() Function

Improve Article
Save Article
  • Last Updated : 03 Nov, 2022
Improve Article
Save Article

The crypto.hkdf() is  an inbuilt application programming interface of class Crypto within crypto module which is used to derive a key of the particular length.

Syntax:

const crypto.hkdf(digest, key, salt, info, keylen, callback)

Parameters: This function takes the following arguments as the parameter.

  • digest: It’s a string of digest algorithm.
  • key: It is the secret key
  • salt: It contains important values.
  • info: It contains extra information.
  • keylen: It’s the length of the key to be generated.
  • callback: It is for further operations.

Return Value: This function returns a derived key of the particular length.

Example 1:

index.js




// Node.js program to demonstrate the  
// crypto.hkdf() function
  
// Importing crypto module
const crypto = require('crypto')
  
// getting derived key 
// by using hkdf() method
const val = crypto.hkdf('sha512', 'key', 'salt'
                        'info', 64, (err, derivedKey) => {
  
    // checking if any error is found
    if (err) throw err;
  
    // display the result
    console.log(Buffer.from(derivedKey).toString('hex'));
  });


Run the index.js file using the following command.

node index.js

Output:

24156e2c35525baaf3d0fbb92b734c8032a110a3f12e25
96e441e1924870d84c3a500652a723738024432451046fd237e
fad8392fb686c5277a59e0105391653

Example 2:

index.js




// Node.js program to demonstrate the  
// crypto.hkdf() function
  
// Importing crypto module
const crypto = require('crypto')
  
// creating and initializing array buffer
const key = new ArrayBuffer(8);
  
// getting derived key 
// by using hkdf() method
const val = crypto.hkdf('sha512', key, 'salt'
                        'info', 32, (err, derivedKey) => {
  
    // checking if any error is found
    if (err) throw err;
  
    // display the result
    console.log(Buffer.from(derivedKey).toString('hex'));
  });


Run the index.js file using the following command.

node index.js

Output:

bb105ac3235f285bd53b68cb95bf78c7fe5f3
a7924ac64d291f68ba2bd0430e1

Reference: https://nodejs.org/dist/latest-v15.x/docs/api/crypto.html#crypto_crypto_hkdf_digest_key_salt_info_keylen_callback


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!