NPM 'crypto' 返回与在线生成器(节点)不同的哈希值

NPM 'crypto' returning different hash values than online generators (node)

我可能没有正确使用 crypto 模块,也许有人可以帮助我。

目标是找到 dropzone 中删除的文件的 sha-256 哈希值。问题是返回的散列与在线散列检查器(返回看似正确的值)不同。这是我的代码:

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

handleOnDrop = file => {
    hash.update(file);
    const hashOutput = hash.digest("hex");
    console.log(hashOutput);
  };

加密文档 - https://nodejs.org/api/crypto.html#crypto_node_js_crypto_constants

我相当确定我从这段代码中得到的哈希值不仅仅是文件名,我用在线检查器检查了一些排列。

有什么想法吗?谢谢!

Dropzone 事件 return File class object, this object is based on the Blob class and doesn't provide direct access to the data of the file. In order to use the data in the file, you must use the FileReader class as outlined in the Mozilla examples

当您调用 hash.update 时,Crypto 需要一个缓冲区,但 file 不是像 examples 中那样的缓冲区。将 Blob 放入 hash.update 中可能没有您期望的行为。

因此,假设您使用 WebPack 来提供对 Node 标准库的访问,您的代码应该需要执行如下操作:

  handleOnDrop = ((file) => {
    const reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = ((event) => {
      hash.update(Buffer.from(event.target.result));
      const hashOutput = hash.digest("hex");
      console.log(hashOutput);
    });
  });