Node.js 中的 crypto.pbkdf2() 方法


crypto.pbkdf2(),也稱為基於密碼的金鑰派生函式,提供了派生函式的非同步實現。透過使用指定演算法的 Hmac 摘要從密碼、鹽和迭代次數派生金鑰。

語法

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

引數

以上引數描述如下:

  • password – 定義用於獲取請求位元組長度金鑰的密碼。可能的值為字串、DataView、Buffer 等型別。

  • salt – 與密碼類似,用於獲取金鑰。可能的值為字串、DataView、Buffer 等型別。

  • iterations – 獲取請求位元組長度的所需金鑰。它接受數值作為值。

  • keylen – 這是金鑰的請求位元組長度。它是數字型別。

  • digest – 此摘要值指定 Hmac 演算法。預設值為“sha1”。

  • callback – 如果在非同步模式下發生任何錯誤,它將在回撥中處理。

示例

建立一個名為 pbkdf2.js 的檔案並複製以下程式碼片段。建立檔案後,使用以下命令執行此程式碼,如以下示例所示:

node pbkdf2.js

pbkdf2.js

 線上演示

// crypto.pbkdf2() demo example

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

// Defining the pbkdf2 with the following options
crypto.pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
   if (err) throw err;
   // Printing the derived key
   console.log("Key Derived: ",derivedKey.toString('hex'));
});

輸出

C:\home
ode>> node pbkdf2.js Key Derived: 3745e482c6e0ade35da10139e797157f4a5da669dad7d5da88ef87e47471cc47ed941c7ad618e8 27304f083f8707f12b7cfdd5f489b782f10cc269e3c08d59ae

示例

讓我們再看一個例子。

 線上演示

// crypto.pbkdf2() demo example

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

// Defining the pbkdf2 with the following options
crypto.pbkdf2('secret', 'salt', 100, 64, 'sha1', (err, derivedKey) => {
   if (err) throw err;
   // Printing the derived key
   console.log("Key Derived: ",derivedKey);
   console.log("Key Derived in hex: ",derivedKey.toString('hex'));
   console.log("Key Derived in base64: ",derivedKey.toString('base64'));
});

輸出

C:\home
ode>> node pbkdf2.js Key Derived: <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 3d 23 19 13 2d 84 e1 91 a7 83 e2 00 73 4e 37 4a 24 b6 ... > Key Derived in hex: b73635f7c0882e1fc3ba6e29b14af1274df84828b4d18fcc222eb574455f505d3d2319132d84e1 91a783e200734e374a24b62cfab65dfb5e9dc28ae147072419 Key Derived in base64: tzY198CILh/Dum4psUrxJ034SCi00Y/MIi61dEVfUF09IxkTLYThkaeD4gBzTjdKJLYs+rZd+16dwo rhRwckGQ==

更新於: 2021年5月20日

1K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.