[英]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.