Using crypto node.js Library, unable to create SHA-256 Hashes multiple times in rapid succession

Viewed 11293

I am creating a hash of an auto-incrementing number. I have created two example loops of how I'm trying to achieve this.

When #1 is is run, the first hash is logged to the console and on the second iteration through the loop, the following error is returned. Error: Digest already called

I believe this is due to this reference in the documentation: The Hash object can not be used again after hash.digest() method has been called. Multiple calls will cause an error to be thrown.

How can I create a loop that uses Node's crypto library to create multiple hashes at one time?

 // Reproduce #1
 const crypto = require('crypto');

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

 for (let i = 0; i < 5; i++) {
   hash.update('secret' + i);

   console.log(hash.digest('hex'));
 }
2 Answers

A clean way to do it without having to repeat const H = crypto.createHash('sha256') on every instance is to use hash.copy() -

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

 for (let i = 0; i < 5; i++) {
   hash.update('secret' + i);
   console.log(hash.copy().digest('hex'));
 }

You get the desired output -

e7ebc4daa65343449285b5736ebe98a575c50ce337e86055683452d7d612ac78
3dc562fa371a320efb0cca0ae344c8a5bddfcd3d5191cd124798404b729423c2
7547b5c1992ed566a2125817b2c76ed4a7d3c551232904f886bd954e649e3144
b49247304dc3ef76d9ebfd0482bfc68ab9b7b0fe2007b7c60e03ad6b8123be33
82bc2bcfc528fd55807a981c79e0b6aa430a690b51de79d9d0c5f5627864965b
Related