const crypto = require('crypto');
// Data to authenticate
const data = 'Data to authenticate with HMAC';
// Function to create HMAC with different key types
function createHmacWithKey(algorithm, data, key, keyType) {
const hmac = crypto.createHmac(algorithm, key);
hmac.update(data);
return {
keyType,
hmac: hmac.digest('hex')
};
}
console.log(`Data: "${data}"`);
console.log('------------------------------------');
// 1. String key
const stringKey = 'my-secret-key';
console.log(createHmacWithKey('sha256', data, stringKey, 'String key'));
// 2. Buffer key
const bufferKey = Buffer.from('buffer-secret-key');
console.log(createHmacWithKey('sha256', data, bufferKey, 'Buffer key'));
// 3. TypedArray key
const uint8ArrayKey = new Uint8Array([72, 101, 108, 108, 111]); // "Hello" in ASCII
console.log(createHmacWithKey('sha256', data, uint8ArrayKey, 'Uint8Array key'));
// 4. DataView key
const arrayBuffer = new ArrayBuffer(5);
const dataView = new DataView(arrayBuffer);
dataView.setUint8(0, 72); // H
dataView.setUint8(1, 101); // e
dataView.setUint8(2, 108); // l
dataView.setUint8(3, 108); // l
dataView.setUint8(4, 111); // o
console.log(createHmacWithKey('sha256', data, dataView, 'DataView key'));
// 5. KeyObject (recommended for sensitive keys)
const keyObject = crypto.createSecretKey(Buffer.from('key-object-secret'));
console.log(createHmacWithKey('sha256', data, keyObject, 'KeyObject'));