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\node>> 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\node>> node createHash.js d1bd739234aa1ede5acfaccee657296ead1879644764f45be17466a9192c3967 /home/node/test/createHash.js