Security
Node.js crypto HMAC
Cryptographic primitives protect different properties. A hash produces a digest of data; a message authentication code (MAC) uses a shared secret to check integrity and authenticity; a digital signature uses a private signing key and corresponding public verification key. Encryption provides confidentiality, and authenticated encryption also checks integrity. Do not use a fast digest for password storage. Do not treat Base64 as encryption. Do not construct custom authentication protocols from primitives merely because individual operations pass tests. Evidence: local teaching fixture, not a production security guarantee. Source: https://nodejs.org/download/release/v22.16.0/docs/api/crypto.html
Formal Syntax & Structure
nodejs syntaxnodejs
createHmac(algorithm, key[, options]).update(data).digest([encoding])Working Example
Example Snippetnodejs
import {createHash,createHmac,randomBytes,timingSafeEqual} from 'node:crypto';const message = 'inventory:2';const digest = createHash('sha256').update(message).digest();const key = randomBytes(32); // Disposable for this run.const mac = value => createHmac('sha256',key).update(value).digest();console.log(digest.length);console.log(timingSafeEqual(mac(message),mac(message)));console.log(timingSafeEqual(mac(message),mac('inventory:3')));