Search code examples
node.jsnode-crypto

Using SHA-256 with NodeJS Crypto


I'm trying to hash a variable in NodeJS like so:

var crypto = require('crypto');

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

var code = 'bacon';

code = hash.update(code);
code = hash.digest(code);

console.log(code);

But looks like I have misunderstood the docs as the console.log doesn't log a hashed version of bacon but just some information about SlowBuffer.

What's the correct way to do this?


Solution

  • digest returns the hash by default in a Buffer. It takes a single parameter which allows you to tell it which encoding to use. In your code example, you incorrectly passed the encoding bacon to digest. To fix this, you need only to pass a valid encoding to the digest(encoding) function.

    base64:

    const { createHash } = require('crypto');
    createHash('sha256').update('bacon').digest('base64');
    
    // nMoHAzQuJIBqn2TgjAU9yn8s2Q8QUpr46ocq+woMd9Q=
    

    hex:

    const { createHash } = require('crypto');
    createHash('sha256').update('bacon').digest('hex');
    
    // 9cca0703342e24806a9f64e08c053dca7f2cd90f10529af8ea872afb0a0c77d4