crypto.createHmac() วิธีการจะสร้างวัตถุ Hmac แล้วส่งคืน Hmac นี้ใช้อัลกอริธึมและคีย์ที่ส่งผ่าน ตัวเลือกเสริมจะใช้ในการควบคุมพฤติกรรมการสตรีม คีย์ที่กำหนดจะเป็นคีย์ HMAC ที่ใช้สำหรับสร้างแฮช HMAC ที่เข้ารหัส
ไวยากรณ์
crypto.createHmac(algorithm, key, [options])
พารามิเตอร์
พารามิเตอร์ข้างต้นอธิบายไว้ด้านล่าง −
-
อัลกอริทึม – อัลกอริธึมนี้ใช้สำหรับสร้างวัตถุ Hmac ประเภทอินพุตเป็นสตริง
-
คีย์ – คีย์ Hmac ใช้สำหรับสร้างแฮช Hmac ที่เข้ารหัส
-
ตัวเลือก – เป็นพารามิเตอร์ทางเลือกที่สามารถใช้ควบคุมพฤติกรรมการสตรีมได้
-
การเข้ารหัส – การเข้ารหัสสตริงที่จะใช้
ตัวอย่าง
สร้างไฟล์ที่มีชื่อ – createHmac.js และคัดลอกข้อมูลโค้ดด้านล่าง หลังจากสร้างไฟล์แล้ว ให้ใช้คำสั่งต่อไปนี้เพื่อเรียกใช้โค้ดนี้ดังแสดงในตัวอย่างด้านล่าง −
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); ผลลัพธ์
C:\home\node>> node createHmac.js Hmac value Obtained is: dd897f858bad70329fad82087110059f5cb920af2736d96277801f70bd57618e
ตัวอย่าง
ลองดูอีกตัวอย่างหนึ่ง
// 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}`);
}
}); ผลลัพธ์
C:\home\node>> node createHmac.js 0489ce5e4bd940c06253764e03927414f79269fe4f91b1c75184dc074fa86e22 /home/node/test/createHmac .js