hash.copy()方法是加密模塊的Hash類的內置函數。此方法用於複製哈希的當前狀態。可以多次調用此方法以創建哈希的多個副本。如果在調用digest方法之後調用此方法,則將引發錯誤。
此函數采用一個可選參數來控製流行為,例如“輸出長度”。
用法:
hash.copy([,Optional ])
參數:此函數采用一個可選參數:
- 。數據流行為。
返回值:此方法返回哈希的當前狀態的副本。
模塊安裝:使用以下命令安裝所需的模塊:
npm install crypto
範例1:僅一次複製哈希值。
index.js
// Importing crypto module
const crypto = require('crypto');
// Creating Hash instance with createHash
const hash = crypto.createHash('sha256');
// use update to add data
hash.update('I love GeeksForGeeks');
// Making the copy of the current hash
const hashCopy = hash.copy();
// Printing the hash value
console.log("Original Hash Value:" + hash.digest('hex'));
console.log("Copied Hash Value:" + hashCopy.digest('hex'));
使用以下命令運行index.js文件:
node index.js
輸出:
Original Hash Value: 5a302d3c930d9e938c5326d7bb863afdc024b9ce77e30e99c4b82983350f8196 Copied Hash Value: 5a302d3c930d9e938c5326d7bb863afdc024b9ce77e30e99c4b82983350f8196
範例2:多次複製哈希。
index.js
const crypto = require('crypto');
// Creating Hash instance with createHash
const hash = crypto.createHash('sha256');
// Adding data to hash
hash.update('I love GeeksForGeeks');
// Making copy of the current hash
const hashCopy1 = hash.copy();
const hashCopy2 = hash.copy();
// Printing the hash value
console.log("Original Hash Value:" + hash.digest('hex'));
console.log("Copy 1:" + hashCopy1.digest('hex'));
console.log("Copy 2:" + hashCopy2.digest('hex'));
使用以下命令運行index.js文件:
node index.js
輸出:
Original Hash Value: 5a302d3c930d9e938c5326d7bb863afdc024b9ce77e30e99c4b82983350f8196 Copy 1: 5a302d3c930d9e938c5326d7bb863afdc024b9ce77e30e99c4b82983350f8196 Copy 2: 5a302d3c930d9e938c5326d7bb863afdc024b9ce77e30e99c4b82983350f8196
範例3:更新複製的哈希值。
index.js
//Importing crypto module
const crypto = require('crypto');
// Creating Hash instance with createHash
const hash = crypto.createHash('sha256');
// Adding data to hash
hash.update('I love GeeksForGeeks');
// Making copy of the current hash
const unchangedCopy = hash.copy();
const updatedCopy = hash.copy();
// Update the old data
updatedCopy.update('Because I love coding')
// Printing the hash value
console.log("Original Hash Value:" + hash.digest('hex'));
console.log("Unchanged Copy:" + unchangedCopy.digest('hex'));
console.log("Updated Copy:" + updatedCopy.digest('hex'));
使用以下命令運行index.js文件:
node index.js
輸出:
Original Hash Value: 5a302d3c930d9e938c5326d7bb863afdc024b9ce77e30e99c4b82983350f8196 Unchanged Copy: 5a302d3c930d9e938c5326d7bb863afdc024b9ce77e30e99c4b82983350f8196 Updated Copy: e0789790d7da870830a679828c722f74f3840d4a6483f5babfb62c4d19884c9e
參考: https://nodejs.org/api/crypto.html#crypto_hash_copy_options
相關用法
- Node.js console.timeLog()用法及代碼示例
- Node.js x509.toLegacyObject()用法及代碼示例
- Node.js fs.fsyncSync()用法及代碼示例
- Node.js process.nextTick()用法及代碼示例
- Node.js GM charcoal()用法及代碼示例
- Node.js GM blur()用法及代碼示例
注:本文由純淨天空篩選整理自adityapande88大神的英文原創作品 Node.js hash.copy() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。