Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เมธอด crypto.createHash() ใน Node.js

เมธอด crypto.createHash() สร้างและคืนค่า hash object ซึ่งนำไปสร้าง hash digest ด้วยอัลกอริทึมที่กำหนด ตัวเลือก options ควบคุมพฤติกรรมสตรีม สำหรับฟังก์ชันแบบ XOF เช่น shake256 ใช้ outputLength กำหนดความยาวเอาต์พุตเป็นไบต์

ไวยากรณ์

crypto.createHash(algorithm, [options])

พารามิเตอร์

  • algorithm – อัลกอริทึมสร้าง hash digest (เช่น sha256, md5)
  • options – ตัวเลือกควบคุมสตรีม (ทางเลือก)

ตัวอย่าง: Hash ข้อความง่ายๆ

const crypto = require('crypto');

const secret = 'TutorialsPoint';
const hashValue = crypto.createHash('sha256', secret)
  .update('Welcome to TutorialsPoint !')
  .digest('hex');

console.log("Hash Obtained is: ", hashValue);

ผลลัพธ์

Hash Obtained is: 5f55ecb1ca233d41dffb6fd9e307d37b9eb4dad472a9e7767e8727132b784461

ตัวอย่าง: Hash ไฟล์ (ใช้ stream)

const crypto = require('crypto');
const fs = require('fs');

const filename = process.argv[1];
const hash = crypto.createHash('sha256', "TutorialsPoint");
const input = fs.createReadStream(filename);

input.on('readable', () => {
  const val = input.read();
  if (val) hash.update(val);
  else {
    console.log(`${hash.digest('hex')} ${filename}`);
  }
});

ผลลัพธ์

d1bd739234aa1ede5acfaccee657296ead1879644764f45be17466a9192c3967 /home/node/test/createHash.js