Mô tả
Phương thức crypto.createHash() sẽ tạo một đối tượng hash và trả về nó. Đối tượng hash này có thể dùng để tạo hash digest bằng thuật toán cho trước. Các tùy chọn tùy chọn dùng để kiểm soát hành vi stream. Đối với một số hàm hash như XOF và 'shake256', độ dài đầu ra dùng để chỉ định độ dài đầu ra mong muốn tính bằng byte.
Cú pháp
crypto.createHash(algorithm, [options])
Tham số
algorithm – Thuật toán dùng để tạo hash digest. Kiểu đầu vào là string.
options – Các tham số tùy chọn dùng để kiểm soát hành vi stream.
Ví dụ
Tạo file tên createHash.js và sao chép đoạn mã dưới. Sau khi tạo file, dùng lệnh sau để chạy:
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);Đầu ra
C:\home\node>> node createHash.js Hash Obtained is: 5f55ecb1ca233d41dffb6fd9e307d37b9eb4dad472a9e7767e8727132b784461
Ví dụ khác
Let's take a look at one more example.
// 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}`); } });Đầu ra
C:\home\node>> node createHash.js d1bd739234aa1ede5acfaccee657296ead1879644764f45be17466a9192c3967 /home/node/test/createHash.js