Open In App

Node.js crypto.scrypt() Method

The crypto.scrypt() method is an inbuilt application programming interface of the crypto module which is used to enable an implementation of an asynchronous script. Where scrypt is a password-based key derivation function. It is intended to be costly computationally plus memory-wise. So, the brute-force attacks are made unsuccessful.

 Syntax:



crypto.scrypt( password, salt, keylen, options, callback )

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

Return Value: It returns a buffer. 



The below examples illustrate the use of crypto.scrypt() method in Node.js: 

Example 1: 




// Node.js program to demonstrate the
// crypto.scrypt() method
 
// Including crypto module
const crypto = require('crypto');
 
// Calling scrypt method with some of its parameter
crypto.scrypt('GfG', 'ffdgsg', 32, (err, derivedKey) => {
 
    if (err) throw err;
 
    // Prints derived key as buffer
    console.log("The derived key1 is :", derivedKey);
});
 
// Calling scrypt method with the parameter N
crypto.scrypt('GeeksforGeeks', 'tfytdx', 128,
    { N: 512 }, (err, derivedKey) => {
 
        if (err) throw err;
 
        // Prints derived key as buffer
        console.log("The derived key2 is :", derivedKey);
        console.log();
    });

Output:

The derived key2 is : <Buffer b3 f8 72 5f 58 df
98 d9 c0 8a ba 0c 2c 50 85 b1 76 de 39 35 40 27 7d
57 f1 6a a1 07 54 dc c9 63 65 32 f2 db 29 95 dc ee
0b 9f e3 d5 0a 9e 3a d0 f6 b4 ... >

The derived key1 is : <Buffer dd 47 ee 3e a8 2e
f2 5b eb 18 7d 35 1b fd f5 a8 e5 f5 38 ef a7 ff 05
53 1e 86 69 ad cd e8 89 76 >

Example 2: 




// Node.js program to demonstrate the
// crypto.scrypt() method
 
// Including crypto module
const crypto = require('crypto');
 
// Defining salt as typed array
const x = new Uint32Array(7);
 
// Calling scrypt method with some of its parameter
crypto.scrypt('yytunnd', x, 16, (err, derivedKey) => {
 
    if (err) throw err;
 
    // Prints derived key which is encoded
    console.log("The derived key1 is :",
        derivedKey.toString("ascii"));
});
 
// Defining salt as data view
const y = new DataView(new ArrayBuffer(5));
 
// Calling scrypt method with the parameter N
crypto.scrypt('oksjdjdn', y, 16, { N: 32 },
    (err, derivedKey) => {
 
        if (err) throw err;
 
        // Prints derived key after encoding
        console.log("The derived key2 is :",
            derivedKey.toString("base64"));
        console.log();
    });

Output:

The derived key2 is : 6Gu0JKHDSHs0tkTuGYuQ7A==
The derived key1 is : G"@&H 
                           pVCD3                               
                                X%

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


Article Tags :