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


crypto.createHash() 方法將建立一個雜湊物件,然後將其返回。該雜湊物件可用於透過給定演算法生成雜湊摘要。可選選項用於控制流行為。對於某些雜湊函式,如 XOF 和“shake256”,輸出長度用於指定以位元組為單位的所需輸出長度。

語法

crypto.createHash(algorithm, [options])

引數

以上引數的說明如下 −

  • 演算法 – 該演算法用於生成雜湊摘要。輸入型別為字串。

  • 選項 – 這些是可選引數,可用於控制流行為。

示例

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

node createHash.js

createHash.js

線上演示

// crypto.createHash() demo example

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

// Deffining the secret key
const secret = 'TutorialsPoint';

// Initializing the createHash method using secret
const hashValue = crypto.createHash('sha256', secret)

   // Data to be encoded
   .update('Welcome to TutorialsPoint !')

   // Defining encoding type
   .digest('hex');
// Printing the output
console.log("Hash Obtained is: ", hashValue);

輸出

C:\home
ode>> node createHash.js Hash Obtained is: 5f55ecb1ca233d41dffb6fd9e307d37b9eb4dad472a9e7767e8727132b784461

示例

我們來看另一示例。

線上演示

// crypto.createHash() demo example

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

// Getting the current file path
const filename = process.argv[1];

// Creting hash for current path using secret
const hash = crypto.createHash('sha256', "TutorialsPoint");

const input = fs.createReadStream(filename);
input.on('readable', () => {
   // Reading single element produced by hash stream.
   const val = input.read();
   if (val)
      hash.update(val);
   else {
      console.log(`${hash.digest('hex')} ${filename}`);
   }
});

輸出

C:\home
ode>> node createHash.js d1bd739234aa1ede5acfaccee657296ead1879644764f45be17466a9192c3967 /home/node/test/createHash.js

更新於: 20-May-2021

2000+ 次瀏覽

開啟 職業生涯

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.