简体   繁体   中英

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 .

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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