如何使用node.js crypto计算blob的sha1哈希值

问题描述 投票:0回答:1

在我的 Node.js 应用程序中,我想上传一个文件并计算 sha1 。

我尝试了以下方法:

export function calculateHash(file, type){
  const reader = new FileReader();
  var hash = crypto.createHash('sha1');
  hash.setEncoding('hex');
  const testfile = reader.readAsDataURL(file);
  hash.write(testfile);
  hash.end();
  var sha1sum = hash.read();
  console.log(sha1sum);
  // fd.on((end) => {
  //   hash.end();
  //   const test = hash.read();
  // });
}

在我的网站上使用文件上传按钮选择文件后,该文件变成了 blob。

如何计算 sha1 哈希值?

javascript node.js hash sha1
1个回答
4
投票

如果您将内容作为一个块来阅读,那么您就会使事情变得比实际需要的更加困难。我们这样做:

const fs = require('fs');
export function calculateHash(file, type){
  const testFile = fs.readFileSync(file);
  var sha1sum = crypto.createHash('sha1').update(testFile).digest("hex");
  console.log(sha1sum);
}
© www.soinside.com 2019 - 2024. All rights reserved.