HMAC with Node.js
[Hashing Home][Home]
HMAC (hash-based message authentication code) supports the usage of a key to hash data. This key is kept secret between Bob and Alice, and can be used to authentication both the data and that the sender still knows the secret. Overall HMAC can be used with a range of different hashing methods, such as MD5, SHA-1, SHA-256 (SHA-2) and SHA-3. This page outlines the HMAC-MD5 methods using the Crypto Node.js library.
|
Theory
HMAC (hash-based message authentication code) supports the usage of a key to hash data. This key is kept secret between Bob and Alice, and can be used to authentication both the data and that the sender still knows the secret. Overall HMAC can be used with a range of different hashing methods, such as MD5, SHA-1, SHA-256 (SHA-2) and SHA-3:
The code is:
const crypto = require("crypto"); var algorithm="sha256"; var message="hello"; var secret="test"; var args = process.argv; if (args.length>2) message=args[2]; if (args.length>3) algorithm=args[3]; if (args.length>4) secret=args[4]; var hash = crypto.createHmac(algorithm,secret); hash.update(message); console.log("Message:\t",message); console.log("Secret:\t\t",secret); console.log("Method:\t\t",algorithm); var myhash = hash.digest('hex'); console.log("\nHMAC is:\t",myhash); hash = crypto.createHash(algorithm); console.log("HMAC is:\t",hash.digest('base64')); console.log("\nLength of HMAC: ",myhash.length*4," bits");
A sample run:
Message: hello Secret: test Method: sha256 HMAC is: f151ea24bda91a18e89b8bb5793ef324b2a02133cce15a28a719acbd2e58a986 HMAC is: 47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU= Length of HMAC: 256 bits