Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'));
 }
like image 410
agm1984 Avatar asked Jun 30 '17 22:06

agm1984


People also ask

How do I create a sha256 hash in node JS?

var crypto = require('crypto'); var hash = crypto. createHash('sha256'); var code = 'bacon'; code = hash. update(code); code = hash. digest(code); console.

What is crypto in node JS How do you cipher the secure information in node JS?

Crypto is a module in Node. js which deals with an algorithm that performs data encryption and decryption. This is used for security purpose like user authentication where storing the password in Database in the encrypted form. Crypto module provides set of classes like hash, HMAC, cipher, decipher, sign, and verify.

How do you use crypto createHash?

The crypto. createHash() method will create a hash object and then return it. THis hash object can be used for generating hash digests by using the given algorithm. The optional options are used for controlling the stream behaviour.


1 Answers

If the error is "Digest already called", then the idea would be to call the Hash only once. You can do that by creating a fresh Hash instance on each iteration:

const crypto = require('crypto');
for (let i = 0; i < 5; i++) {
    const hash = crypto.createHash('sha256');
    hash.update('secret' + i);
    console.log(hash.digest('hex'));
}

Output:

97699b7cc0a0ed83b78b2002f0e57046ee561be6942bec256fe201abba552a9e
5b11618c2e44027877d0cd0921ed166b9f176f50587fc91e7534dd2946db77d6
35224d0d3465d74e855f8d69a136e79c744ea35a675d3393360a327cbf6359a2
e0d9ac7d3719d04d3d68bc463498b0889723c4e70c3549d43681dd8996b7177f
fe2d033fef7942ed06d418992d35ca98feb53943d452f5994f96934d754e15cb
like image 195
Artjom B. Avatar answered Sep 16 '22 19:09

Artjom B.