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


crypto.createHmac() 方法建立一個 Hmac 物件,然後返回該物件。此 Hmac 使用傳遞的演算法和金鑰。可選選項將用於控制流行為。定義的金鑰將用於生成 HMAC 加密雜湊的 HMAC 金鑰。

語法

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

引數

以上引數的說明如下 −

  • 演算法 – 此演算法用於生成 Hmac 物件。輸入型別為字串。

  • 金鑰 – 用於生成 HMAC 加密雜湊的 Hmac 金鑰。

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

  • 編碼 – 要使用的字串編碼。

示例

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

node createHmac.js

createHmac.js

 即時演示

// crypto.createHmac() demo example

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

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

// Initializing the createHmac method using secret
const hmacValue = crypto.createHmac('sha256', secret)

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

   // Defining encoding type
   .digest('hex');

// Printing the output
console.log("Hmac value Obtained is: ", hmacValue);

輸出

C:\home
ode>> node createHmac.js Hmac value Obtained is: dd897f858bad70329fad82087110059f5cb920af2736d96277801f70bd57618e

示例

我們來看一個示例。

 即時演示

// crypto.createHmac() demo example

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

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

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

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

輸出

C:\home
ode>> node createHmac.js 0489ce5e4bd940c06253764e03927414f79269fe4f91b1c75184dc074fa86e22 /home/node/test/createHmac .js

更新於:2021 年 5 月 20 日

2K+ 瀏覽量

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.