เมธอด crypto.createHmac() สร้างและคืนค่า HMAC object ใช้อัลกอริทึมและ key ที่ระบุ ตัวเลือก options ควบคุมพฤติกรรมสตรีม ใช้สร้าง HMAC hash เพื่อความปลอดภัย
ไวยากรณ์
crypto.createHmac(algorithm, key, [options])
พารามิเตอร์
- algorithm – อัลกอริทึม (เช่น
sha256,sha512) - key – HMAC key สำหรับสร้าง hash
- options – ตัวเลือกควบคุมสตรีม (ทางเลือก)
- encoding – string encoding
ตัวอย่าง: HMAC แบบง่าย
const crypto = require('crypto');
const secret = 'TutorialsPoint';
const hmacValue = crypto.createHmac('sha256', secret)
.update('Welcome to TutorialsPoint !')
.digest('hex');
console.log("Hmac value Obtained is: ", hmacValue);
ผลลัพธ์
Hmac value Obtained is: dd897f858bad70329fad82087110059f5cb920af2736d96277801f70bd57618e
ตัวอย่าง: HMAC ของไฟล์ (stream)
const crypto = require('crypto');
const fs = require('fs');
const filename = process.argv[1];
const hmac = crypto.createHmac('sha256', "TutorialsPoint");
const input = fs.createReadStream(filename);
input.on('readable', () => {
const val = input.read();
if (val) hmac.update(val);
else {
console.log(`${hmac.digest('hex')} ${filename}`);
}
});
ผลลัพธ์
0489ce5e4bd940c06253764e03927414f79269fe4f91b1c75184dc074fa86e22 /home/node/test/createHmac.js