Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phương thức crypto.createHmac() trong Node.js

Mô tả

Phương thức crypto.createHmac() sẽ tạo một đối tượng Hmac và trả về nó. Hmac này sử dụng thuật toán và khóa được truyền vào. Các tùy chọn tùy chọn sẽ được dùng để kiểm soát hành vi stream. Khóa được định nghĩa sẽ là khóa HMAC dùng để tạo hash HMAC mật mã.

Cú pháp

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

Tham số

  • algorithm – Thuật toán dùng để tạo đối tượng Hmac. Kiểu đầu vào là string.

  • key – Khóa Hmac dùng để tạo hash HMAC mật mã.

  • options – Các tham số tùy chọn dùng để kiểm soát hành vi stream.

  • encoding – String encoding để sử dụng.

Ví dụ

Tạo file tên createHmac.js và sao chép đoạn mã dưới. Sau khi tạo file, dùng lệnh sau để chạy:

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);

Đầu ra

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

Ví dụ khác

Xem thêm một ví dụ nữa.

// 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}`); } });

Đầu ra

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