const crypto = require('crypto');
const fs = require('fs');
// Function to create HMAC for a file using streams
function createHmacForFile(filePath, algorithm, key) {
return new Promise((resolve, reject) => {
// Create Hmac object
const hmac = crypto.createHmac(algorithm, key);
// Create read stream
const stream = fs.createReadStream(filePath);
// Handle stream events
stream.on('data', (data) => {
hmac.update(data);
});
stream.on('end', () => {
const digest = hmac.digest('hex');
resolve(digest);
});
stream.on('error', (error) => {
reject(error);
});
});
}
// Secret key
const secretKey = 'file-authentication-key';
// Example usage (adjust file path as needed)
const filePath = 'example.txt';
// Create a test file if it doesn't exist
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, 'This is a test file for HMAC authentication.\n'.repeat(100));
console.log(`Created test file: ${filePath}`);
}
// Create HMAC for the file with different algorithms
Promise.all([
createHmacForFile(filePath, 'md5', secretKey),
createHmacForFile(filePath, 'sha1', secretKey),
createHmacForFile(filePath, 'sha256', secretKey)
])
.then(([md5Digest, sha1Digest, sha256Digest]) => {
console.log(`File: ${filePath}`);
console.log(`Secret Key: ${secretKey}`);
console.log(`HMAC-MD5: ${md5Digest}`);
console.log(`HMAC-SHA1: ${sha1Digest}`);
console.log(`HMAC-SHA256: ${sha256Digest}`);
// Store the HMAC for later verification
fs.writeFileSync(`${filePath}.hmac`, sha256Digest);
console.log(`HMAC stored in: ${filePath}.hmac`);
})
.catch(error => {
console.error('Error creating HMAC for file:', error.message);
});