const crypto = require('crypto');
// Data to authenticate
const data = 'Hello, Node.js!';
// Secret key
const secretKey = 'my-secret-key';
// Function to create HMAC and get digest in different encodings
function createHmacWithEncoding(algorithm, data, key, encoding) {
const hmac = crypto.createHmac(algorithm, key);
hmac.update(data);
return hmac.digest(encoding);
}
// Create HMAC with SHA-256 and display in different encodings
console.log(`Data: "${data}"`);
console.log(`Secret Key: "${secretKey}"`);
console.log(`HMAC-SHA256 (hex): ${createHmacWithEncoding('sha256', data, secretKey, 'hex')}`);
console.log(`HMAC-SHA256 (base64): ${createHmacWithEncoding('sha256', data, secretKey, 'base64')}`);
console.log(`HMAC-SHA256 (base64url): ${createHmacWithEncoding('sha256', data, secretKey, 'base64url')}`);
console.log(`HMAC-SHA256 (binary): ${createHmacWithEncoding('sha256', data, secretKey, 'binary')}`);
// Get the digest as a Buffer (no encoding)
const hmac = crypto.createHmac('sha256', secretKey);
hmac.update(data);
const buffer = hmac.digest();
console.log('HMAC-SHA256 (Buffer):', buffer);
console.log('Buffer length:', buffer.length, 'bytes');