admin管理员组

文章数量:1406943

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?

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?

Share Improve this question edited Jun 16, 2016 at 20:41 Artjom B. 62k26 gold badges135 silver badges230 bronze badges asked Jun 16, 2016 at 4:12 user1526912user1526912 17.3k18 gold badges61 silver badges97 bronze badges 2
  • CryptoJS is mainly a client library and should not be confused with node.js' crypto module. Which one is it for you? – Artjom B. Commented Jun 16, 2016 at 20:40
  • What's the issue with the code you've presented here? Doesn't it already work? – Artjom B. Commented Jun 16, 2016 at 20:41
Add a ment  | 

1 Answer 1

Reset to default 5

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

本文标签: javascriptHow to calculate the sha1 hash of a blob using nodejs cryptoStack Overflow