How to generate SHA256HMAC in Node.JS

Today I had to do this for my job (hash some info) and I think is a good opportunity to share the knowledge. Here is the code, you can simply copy it and paste it in a file called SHA256Hmac.js and run it.

let crypto;

try {
    crypto = require('crypto');
} catch (err) {
    console.log('crypto support is disabled!');
}

console.log('crypto is supported!');

const SHA256_ALGORITHM = "sha256";
const key = "secret key";
const hmac = crypto.createHmac(SHA256_ALGORITHM, key);
const data = "This is the data to be digested";

hmac.update(data);
console.log(hmac.digest('hex'));

// Prints: 9abf6309b33253fd11712b46a720bf87cd1eb90282b852680ad3efb2db6f01f5

From console you will have an output like this:

C:experimentsCryptography>node SHA256Hmac.js
crypto is supported!
9abf6309b33253fd11712b46a720bf87cd1eb90282b852680ad3efb2db6f01f5

I hope is useful.

Sources

 

2 thoughts on “How to generate SHA256HMAC in Node.JS

    1. Thanks! 😉

Leave a Comment

Your email address will not be published. Required fields are marked *