How to properly use SHA-256 hashing with Node.js Crypto?
I’m trying to hash a variable in Node.js using the Crypto module:
var crypto = require('crypto');
var hash = crypto.createHash('sha256');
var code = 'bacon';
code = hash.update(code);
code = hash.digest(code);
console.log(code);
However, instead of getting a hashed version of “bacon,” the console logs some information about SlowBuffer. What am I doing wrong, and how can I correctly generate a SHA-256 hash in Node.js?
Make use of the digest() :
var crypto = require('crypto');
var hash = crypto.createHash('sha256');
var code = 'bacon';
hash.update(code);
var hashedCode = hash.digest('hex');
console.log(hashedCode);
You can also make use of Buffer Output :
var crypto = require('crypto');
var hash = crypto.createHash('sha256');
var code = 'bacon';
hash.update(code);
var hashedCode = hash.digest(); // Returns a buffer
console.log(hashedCode.toString('hex')); // Convert buffer to hex
I totally agree with the solutions given by @jacqueline-bosco and @ishrth_fathima you can use stream-based Hashing :
const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('sha256');
const input = fs.createReadStream('path/to/file');
input.pipe(hash).setEncoding('hex').on('finish', () => {
console.log(hash.read());
});