To securely verify the integrity of messages using HMAC (Hash-based Message Authentication Code) in Node.js, both the sender and receiver need to share a secret key and the original data. The HMAC process ensures that the data hasn't been altered and is authentic.
Steps for Implementing HMAC in Node.js
1. Sender Side (Creating the HMAC)
The sender uses the shared secret key and the data to generate the HMAC. This is done using Node.js's crypto.createHmac() method.
const crypto = require('crypto');
const secret = 'abcdefg'; // The shared secret key
const message = 'I love cupcakes'; // The data to be authenticated
// Create the HMAC using SHA-256 (or any secure hash function)
const hash = crypto.createHmac('sha256', secret)
.update(message)
.digest('hex'); // Digest the HMAC as a hexadecimal string
console.log('Generated HMAC:', hash); // This HMAC will be sent with the message
2. Receiver Side (Verifying the HMAC): The receiver verifies the integrity of the received data by recalculating the HMAC with the same secret key and data. If the hashes match, it confirms that the data has not been tampered with.
const receivedHmac = 'received-hmac-from-sender'; // The HMAC received from the sender
const receivedMessage = 'I love cupcakes'; // The received message
// Recalculate the HMAC using the same secret and data
const calculatedHmac = crypto.createHmac('sha256', secret)
.update(receivedMessage)
.digest('hex');
// Compare the calculated HMAC with the received one
if (calculatedHmac === receivedHmac) {
console.log('Message integrity verified');
} else {
console.log('Message integrity check failed');
}