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

点点圈 提交于 2020-01-07 02:13:29

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/37849779/how-to-calculate-the-sha1-hash-of-a-blob-using-node-js-crypto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!