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

 

Advertisements

2 comments

  1. nice one bro!!!

    1. Thanks! 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: