To hash a payload with nodejs, I can use the crypto module and do:
const crypto = require('crypto');
const payload = "abc123";
const hashObj = crypto.createHash('sha256');
const res = hashObj.update(payload).digest('hex');
Now say I want to hash a second payload, could I safely reuse the hashObj
I just instantiated and call update
and digest
on it with the new payload? Or do I have to call createHash
for every payload?
Edit: To clarify, by reuse I mean extending the above code to the following for example:
const crypto = require('crypto');
const payload1 = "abc123";
const payload2 = "def456";
const hashObj = crypto.createHash('sha256');
const res1 = hashObj.update(payload1).digest('hex');
const res2 = hashObj.update(payload2).digest('hex');
CodePudding user response:
The hasher does not reset, calling update()
only adds more data to the hasher. So this:
const res1 = hashObj.update(payload1).digest('hex');
const res2 = hashObj.update(payload2).digest('hex');
would assign the hash for payload1
to res1
, and the digest for payload1 payload2
to res2
, except for the part where calling .digest()
finalizes the hasher:
The Hash object can not be used again after hash.digest() method has been called. Multiple calls will cause an error to be thrown.
So for any discrete piece of data, you need a separate hasher, and for any data stream you can update()
as much as you need to, and then you call .digest()
once you have everything packed up.