Open In App

Node.js crypto.hkdfSync( ) Method

Last Updated : 08 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

This method provides a synchronous HMAC-based Extract-and-Expand Key Derivation Function key derivation. Key of keylen bytes is derived using digest, given key, salt and info.

Syntax:

crypto.hkdfSync(digest, key, salt, info, keylen)

Parameters: This method has five parameters.

  • digest: It must be string.
  • key: Minimum lengths — 1 byte, It is of type string, Buffer,ArrayBuffer, TypedArray, KeyObject or DataView.
  • salt: It must be provided but can be zero-length and unique. It can be of type string, ArrayBuffer, Buffer, TypedArray, or DataView.
  • info: It must be provided but can be zero-length and cannot be more than 1024 bytes. It is of type string, Buffer,ArrayBuffer, TypedArray, KeyObject or DataView.
  • keylen: It is the length of the key to generate and must be greater than 0. It must b of type number.

Return Type: Returns derived key int the form of buffer.

Example 1: app.js
// Node.js program to demonstrate the
//  crypto.hkdfSync() Method.

// // Including crypto module 
import crypto from 'crypto'

//Implementing hkdfSync()
const Key = crypto.hkdfSync('sha512', 'key', 'salt', 'info', 64);

// Prints Buffer.
console.log(Key);
Output:
ArrayBuffer {
 [Uint8Contents]: <24 15 6e 2c 35 52 5b 
 aa f3 d0 fb b9 2b 73 4c 80 32 a1 10 a3 f1 2e 
 25 96 e4 41 e1 92 48 70 d8 4c 3a 50 06 52 a7 
 23 73 80 24 43 24 51 04 6f d2 37 ef ad 83 92 
 fb 68 6c 52 77 a5 9e 01 05 39 16 53>,
 byteLength: 64
}
Example 2: app.js
// Node.js program to demonstrate the
// crypto.hkdfSync() Method.

// Including crypto module 
import crypto from 'crypto'

// Implementing hkdfSync()
const Key = crypto.hkdfSync('sha512', 'key', 'salt', 'info', 16);

// Prints Buffer.
console.log(Buffer.from(Key).toString('hex'));
Output:
24156e2c35525baaf3d0fbb92b734c80
Example 3: JavaScript
// Node.js program to demonstrate the
// crypto.hkdfSync() Method.

// Including crypto module 
import crypto from 'crypto'

//Implementing hkdfSync()
const Key = crypto.hkdfSync('sha512', 'key', 'salt', 'info', 32);

// Prints Buffer.
console.log(Buffer.from(Key).toString('base64'));
Output:
JBVuLDVSW6rz0Pu5K3NMgDKhEKPxLiWW5EHhkkhw2Ew=
Example 4: JavaScript
// Node.js program to demonstrate the
// crypto.hkdfSync() Method.

// Including crypto module 
import crypto from 'crypto'

// Implementing hkdfSync()
const Key = crypto.hkdfSync('sha512', 'key', 'salt', 'info', 32);

// Prints Buffer.
console.log(Buffer.from(Key).toString('ascii'));
Output:
$n,5R[*sP{9+sL 2!#q.%dAaHpXL

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


Next Article

Similar Reads