crypto.pbkdf2()方法提供了一個基於密碼的異步 key 派生函數2即(PBKDF2)實現。此外,實現了由摘要定義的特定HMAC摘要算法,以從所述密碼,密碼和迭代中得出所需字節長度的 key (keylen)。
用法:
crypto.pbkdf2( password, salt, iterations, keylen, digest, callback )
參數:此方法接受上述和以下所述的六個參數:
- password:它可以保存字符串,Buffer,TypedArray或DataView類型的數據。
 - salt:它必須盡可能唯一。但是,建議鹽是任意的,並且在任何情況下至少應為16個字節長。它的類型為字符串,緩衝區,TypedArray或DataView。
 - iterations:它必須是一個數字,並應設置得盡可能高。因此,迭代次數越多,派生 key 將越安全,但是在這種情況下,需要花費更多時間才能完成。它是數字類型。
 - keylen:它是所需字節長度的 key ,並且是數字類型。
 - digest:它是字符串類型的摘要算法。
 - callback:它是一個具有兩個參數的函數,即err和DerivedKey。
 
返回類型:它返回派生的基於密碼的 key 。
下麵的示例說明在Node.js中使用crypto.pbkdf2()方法:
範例1:
// Node.js program to demonstrate the  
// crypto.pbkdf2() method 
  
// Including crypto module 
const crypto = require('crypto'); 
  
// Implementing pbkdf2 with all its parameters 
crypto.pbkdf2('secret', 'salt', 100000, 64, 
         'sha512', (err, derivedKey) => { 
  
  if (err) throw err; 
  
  // Prints derivedKey 
  console.log(derivedKey.toString('hex')); 
});輸出:
3745e482c6e0ade35da10139e797157f4a5da669dad7d5da88ef87e 47471cc47ed941c7ad618e827304f083f8707f12b7cfdd5f489b782 f10cc269e3c08d59ae
範例2:
// Node.js program to demonstrate the  
// crypto.pbkdf2() method 
  
// Including crypto module 
const crypto = require('crypto'); 
  
// Implementing pbkdf2 with all its parameters 
// but digest is null 
crypto.pbkdf2('secret', 'salt', 677, 6, 
          null, (err, derivedKey) => { 
  
  if (err)  
  { 
    console.log(err); 
  }  
  else
  { 
  
  // Prints derivedKey without encoding 
  console.log(derivedKey); 
      
     } 
});    輸出:在此,由於派生鍵未更改為字符串,因此返回緩衝區。
Buffer 71 1e 7b 7b 9b 53
相關用法
- Node.js GM quality()用法及代碼示例
 - Node.js GM resize()用法及代碼示例
 - Node.js GM chop()用法及代碼示例
 - Node.js GM drawPolyline()用法及代碼示例
 - Node.js GM raise()用法及代碼示例
 - Node.js GM paint()用法及代碼示例
 - Node.js GM flop()用法及代碼示例
 - Node.js GM segment()用法及代碼示例
 - Node.js GM drawArc()用法及代碼示例
 
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Node.js | crypto.pbkdf2() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
