134

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?

gevorg
  • 4,835
  • 4
  • 35
  • 52
Cameron
  • 27,963
  • 100
  • 281
  • 483
  • What this digest does ? – Ravi Soni Nov 22 '17 at 11:53
  • Here are [examples from projects for doing md5 hashing](https://www.codota.com/code/javascript/query/crypto@@createHash+crypto@Hash@digest+crypto@Hash@update) - replace 'md5' with 'sha256' to get what you need. – drorw Apr 22 '19 at 12:58
  • Does this answer your question? [node.js hash string?](https://stackoverflow.com/questions/5878682/node-js-hash-string) – sdgfsdh Dec 04 '19 at 11:46

5 Answers5

270

Note that there's something weird about crypto's base64 digest (cause it seems that it returns hex by default).

Compared to sha256

base64:

const sha256 = require('sha256');
const { createHash } = require('crypto');

Buffer.from(sha256('bacon')).toString('base64');               // OWNjYTA3MD...
createHash('sha256').update('bacon').digest('base64');         // nMoHAzQuJI...

// This works though if you really don't want to install external libs:

Buffer.from(createHash('sha256').update('bacon').digest('hex')).toString('base64'); // OWNjYTA3MD...

hex:

const sha256 = require('sha256');
const { createHash } = require('crypto');

sha256('bacon');                                    // 9cca070334...
createHash('sha256').update('bacon').digest('hex'); // 9cca070334...
ArnonZ
  • 3,822
  • 4
  • 32
  • 42
MaximeF
  • 4,913
  • 4
  • 37
  • 51
  • 24
    Don't hash passwords with sha256? Look up bcrypt or something similar. – Dmitry Minkovsky May 07 '20 at 14:24
  • See https://nodejs.org/api/crypto.html – Ryan May 11 '22 at 13:04
  • Can we follow this method in angular? I tried this in an angular project and it didn't work.. – Ish May 20 '22 at 05:42
  • @Ish crypto is a Node module. Node is a server runtime. Assuming that you're running Angular in the browser, you'll need to use browser APIs: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest – mirichan May 29 '22 at 18:45
  • `var CryptoJS = require("crypto-js");` `var hmac = CryptoJS.HmacSHA256(stringToBeHashed, secretKey);` `var hash = hmac.toString(CryptoJS.enc.Hex);` This worked for me. Thanks @mirichan – Ish Jun 04 '22 at 05:09
  • I'm not sure how this answer has so many upvotes considering the hash is wrong. the correct base64 encoded, sha256 hash of 'bacon' is actually the one starting with "nMoHAzQuJI..." *NOT* the one starting with "OWNjYTA3MD..."... the crypto lib is doing exactly what you are telling it.. create a hash of bacon and encode it in base64 which gives "nMoHAzQuJIBqn2TgjAU9yn8s2Q8QUpr46ocq+woMd9Q=" – masonCherry May 01 '23 at 00:48
6

you can use, like this, in here create a reset token (resetToken), this token is used to create a hex version.in database, you can store hex version.

// Generate token
 const resetToken = crypto.randomBytes(20).toString('hex');
// Hash token and set to resetPasswordToken field
this.resetPasswordToken = crypto
    .createHash('sha256')
    .update(resetToken)
    .digest('hex');

console.log(resetToken )
4

nodejs (8) ref

const crypto = require('crypto');
const hash = crypto.createHash('sha256');

hash.on('readable', () => {
    const data = hash.read();
    if (data) {
        console.log(data.toString('hex'));
        // Prints:
        //  6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
    }
});

hash.write('some data to hash');
hash.end();
Mohamed.Abdo
  • 2,054
  • 1
  • 19
  • 12
2

Similar to the answers above, but this shows how to do multiple writes; for example if you read line-by-line from a file and then add each line to the hash computation as a separate operation.

In my example, I also trim newlines / skip empty lines (optional):

const {createHash} = require('crypto');

// lines: array of strings
function computeSHA256(lines) {
  const hash = createHash('sha256');
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim(); // remove leading/trailing whitespace
    if (line === '') continue; // skip empty lines
    hash.write(line); // write a single line to the buffer
  }

  return hash.digest('base64'); // returns hash as string
}

I use this code ensure generated lines of a file aren't edited by someone manually. To do this, I write the lines out, append a line like sha256:<hash> with the sha265-sum, and then, upon next run, verify the hash of those lines matches said sha265-sum.

Blaskovicz
  • 6,122
  • 7
  • 41
  • 50
2

Other way:

const {createHash} = require('node:crypto');
const result = createHash('sha256').update("bacon").digest('hex');
console.log(result);
Silvio Guedes
  • 1,134
  • 15
  • 16