Node.js hmac.update()方法

Node.js hmac.update()方法

hmac.update() 方法是在crypto模块内部HMAC类的内置方法,用于更新hmac对象的数据。

语法:

hmac.update(data[, inputEncoding])

参数: 此方法接受以下两个参数:

  • data: 可以是字符串、缓冲区、TypedArray或DataView类型。它是传递给此函数的数据。
  • inputEncoding: 这是一个可选参数。它是数据字符串的编码。

返回值: 此方法不返回任何内容。

项目设置: 创建一个新的NodeJS项目并命名为 hmac

mkdir hmac && cd hmac
npm init -y

现在在你的项目根目录中创建一个 .js 文件,并将其命名为 index.js

示例1:

index.js

// Node.js program to demonstrate the 
// crypto hmac.update() method 
    
// Importing crypto module 
const { createHmac } = require('crypto') 
  
// Creating and initializing algorithm and password 
const algo = 'sha256'
const secret = 'GFG Secret Key'
  
// Create an HMAC instance 
const hmac = createHmac(algo, secret) 
  
// Update the internal state of the hmac object 
hmac.update('GeeksForGeeks') 
  
// Perform the final operations 
// Return calculated hash 
const result = hmac.digest('base64') 
  
// Print the result 
console.log(`HMAC hash: ${result}`) 

运行以下命令使用 index.js 文件:

node index.js

输出:

HMAC hash: yK4+CYVa56w0Ba1g2TdY7cDM68HPXFKb+10FhnRpXFM=

示例 2:

index.js

// Node.js program to demonstrate the     
// crypto hmac.update() method 
  
// Defining myfile 
const myfile = process.argv[2]; 
  
// Includes crypto and fs module 
const crypto = require('crypto'); 
const fs = require('fs'); 
  
// Creating and initializing algorithm and password 
const algo = 'sha256'
const secret = 'GFG Secret Key'
  
// Creating Hmac 
const hmac = crypto.createHmac(algo, secret); 
  
// Creating read stream 
const readfile = fs.createReadStream(myfile); 
  
readfile.on('readable', () => { 
  
  // Calling read method to read data 
  const data = readfile.read(); 
  
  if (data) 
  
    // Updating 
    hmac.update(data); 
  else { 
  
    // Perform the final operations  
    // Return hash value 
    const result = hmac.digest('hex') 
  
    // Display result 
    console.log(`HMAC hash value of {myfile}:{result}`); 
  } 
});

使用以下命令运行 index.js 文件:

node index.js package.json

输出:

package.json的HMAC哈希值: 38f0f975f8964343c24da940188eaeb6bb20842e3c5bf03ccb66773e98beeb73

参考: https://nodejs.org/api/crypto.html#crypto_hmac_update_data_inputencoding

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程