Useful piece of code to produce a 256-bit hash value with SHA-256:

There a few JavaScript implementation of the SHA-256 hash function out there. But the easiest is usually to use Node’s built in cryptography module.

The Code

If you just need the code, here it is:

var crypto = require('crypto');

var hash = crypto.createHash('sha256')
.update(inputString)
.digest('hex');

Details

Generate the hash

Import the crypto module and use the createHash function to generate the hash.

var crypto = require('crypto');

var hash = crypto.createHash('sha256');

Hash your value

Use the update function on the hash object instance to process your input.

hash.update('CodeBlocQ');

Output

Use the digest function on the hash to ouput the value. You can pass ‘hex’, ‘binary’ or ‘base64’ to get the result in the desired encoding.

Hex

var hex = hash.digest('hex');
console.log(hex); // c5d44424ef47ab9e1806d9c1a3045942cfd06e0ec5e798449c02e44e9ae38292

Binary

var bin = hash.digest('binary');
console.log(bin); // ÅÔD$ïG«žÙÁ£YBÏÐnÅç˜DœäNšã‚’

Base64

var base64 = hash.digest('base64');
console.log(base64); // xdREJO9Hq54YBtnBowRZQs/Qbg7F55hEnALkTprjgpI=