简体   繁体   English

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

[英]How to calculate the sha1 hash of a blob using node.js crypto

In my node.js app I would like to upload a file and calculate the sha1 . 在我的node.js应用程序中,我想上传一个文件并计算sha1。

I tried the following : 我尝试了以下方法:

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

The file is blob from selecting a file with a file upload button on my website. 该文件是通过在我的网站上选择带有文件上传按钮的文件而获得的。

How can I calculate the sha1 hash? 如何计算sha1哈希?

if you're reading the contents in as a block, you're making this harder than it needs to be. 如果您以块的形式阅读内容,则会使此工作变得比其所需的难度更大。 We do this: 我们这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM