簡體   English   中英

使用 crypto node.js 庫,無法快速連續多次創建 SHA-256 哈希

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

我正在創建一個自動遞增數字的哈希。 我創建了兩個示例循環來說明我如何嘗試實現這一目標。

當 #1 運行時,第一個散列被記錄到控制台,在循環的第二次迭代中,返回以下錯誤。 錯誤:摘要已調用

我相信這是由於文檔中的這個引用:調用 hash.digest() 方法后無法再次使用 Hash 對象。 多次調用會導致拋出錯誤。

如何創建一個循環,使用 Node 的加密庫一次創建多個哈希?

 // 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'));
 }

如果錯誤是“摘要已經調用”,那么這個想法就是只調用一次哈希。 您可以通過在每次迭代時創建一個新的 Hash 實例來做到這一點:

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'));
}

輸出:

97699b7cc0a0ed83b78b2002f0e57046ee561be6942bec256fe201abba552a9e
5b11618c2e44027877d0cd0921ed166b9f176f50587fc91e7534dd2946db77d6
35224d0d3465d74e855f8d69a136e79c744ea35a675d3393360a327cbf6359a2
e0d9ac7d3719d04d3d68bc463498b0889723c4e70c3549d43681dd8996b7177f
fe2d033fef7942ed06d418992d35ca98feb53943d452f5994f96934d754e15cb

無需在每個實例上重復const H = crypto.createHash('sha256')的干凈方法是使用 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'));
 }

你得到了想要的輸出 -

e7ebc4daa65343449285b5736ebe98a575c50ce337e86055683452d7d612ac78
3dc562fa371a320efb0cca0ae344c8a5bddfcd3d5191cd124798404b729423c2
7547b5c1992ed566a2125817b2c76ed4a7d3c551232904f886bd954e649e3144
b49247304dc3ef76d9ebfd0482bfc68ab9b7b0fe2007b7c60e03ad6b8123be33
82bc2bcfc528fd55807a981c79e0b6aa430a690b51de79d9d0c5f5627864965b

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM