當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js hash.update()用法及代碼示例

hash.update()方法是加密模塊的Hash類的內置函數。這用於用給定的數據更新哈希。可以多次調用此方法以更新哈希的內容,因為此方法可以獲取流數據,例如文件讀取流。

此函數將數據作為生成哈希的參數,它可以是字符串或文件對象。與數據一起,這也需要數據的編碼類型,可以是utf-8,二進製或ASCII。如果未提供編碼並且data是字符串,則使用utf-8。所需的輸出長度(以字節為單位)。

模塊安裝:使用以下命令安裝所需的模塊:

npm install crypto

用法:

hash.update(data [,Encoding])

參數:此函數采用以下兩個參數:



  • data:需要添加到哈希中的數據。
  • encoding:數據的編碼類型。

返回值:此方法返回具有更新數據的對象。

範例1:

Javascript


// Import crypto module
const crypto = require('crypto');
  
// Create Hash instance with createHash
var hash = crypto.createHash('sha256')
                            // Use update to add data
                            .update('I love GeeksForGeeks')
  
                            // Use digest to get the hash value
                            .digest('hex');
  
// Prints the hash value
console.log("Hash Value:" + hash);

輸出:

Hash Value:5a302d3c930d9e938c5326d7bb863afdc024b9ce77e30e99c4b82983350f8196

範例2:

Javascript


// Import crypto module
const crypto = require('crypto');
  
// Create Hash instance with createHash
var hash = crypto.createHash('sha256')
                            // Use update to add data
                            .update('I love GeeksForGeeks')
  
                            // Use update to add data
                            .update('Because I love coding')
  
                            // Use digest to get the hash value
                            .digest('hex');
  
// Prints the hash value
console.log("Hash Value:" + hash);

輸出:

Hash Value:e0789790d7da870830a679828c722f74f3840d4a6483f5babfb62c4d19884c9e

參考: https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding

相關用法


注:本文由純淨天空篩選整理自adityapande88大神的英文原創作品 Node.js hash.update() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。