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

use*_*912 4 javascript hash sha1 node.js

在我的 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();
  // });
}
Run Code Online (Sandbox Code Playgroud)

该文件是通过在我的网站上使用文件上传按钮选择文件而形成的。

如何计算 sha1 哈希值?

Bob*_*son 5

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

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);
}
Run Code Online (Sandbox Code Playgroud)