【问题标题】:How to calculate the checksum of a file in browser and get the same results as from windows command prompt如何在浏览器中计算文件的校验和并获得与 Windows 命令提示符相同的结果
【发布时间】:2016-10-19 22:23:06
【问题描述】:

我正在尝试从网页上上传的文件中获取校验和/哈希。

我目前可以通过浏览器上传文件,然后使用 node.js 加密库计算哈希。我首先将 blob 转换为数据 Url。

export function calculateHash(dataUrl, type){

  const sha1sum = crypto.createHash('sha1').update(dataUrl).digest("hex");
  console.log('Hash sum is ' + sha1sum);

}

结果:66b8bdd2d1d49f708722c15b26409bc072096697

当我使用以下命令从 windows 命令提示符手动计算哈希时..

fciv.exe 1_1.wav -sha1

结果:b06071b13a1b50cd2976ed7bb4180f6963e8db8e

我想从浏览器中的数据 url 获得与在命令提示符下进行手动检查相同的校验和结果。

这可能吗?

【问题讨论】:

  • 您在此处展示的代码来自 node.js 的加密模块。这与浏览器或 [cryptojs] 无关!由于这似乎是服务器代码,你如何调用你的calculateHash 函数?该功能的输入是什么?你能举一些例子吗?这与comment 对您之前的问题的评论基本相同。
  • Node.js 代码运行在服务器上,只通过请求与浏览器通信。你使用什么样的请求?你读过What is the difference between client-side and server-side programming?

标签: javascript node.js hash sha1


【解决方案1】:

数据 url 看起来像 data:image/png;base64,<BASE-64 DATA>。您需要提取 BASE-64 DATA 部分,解码 base64,然后运行您的散列算法。或者 - 如果你想在浏览器中执行散列 - 使用 FileReader API:

function calculateHash(file, callback) {  
  let reader = new FileReader();
  reader.onload = function(event) {
    let file_sha1 = sha1(reader.result);
    callback(file_sha1);
  };
  reader.readAsArrayBuffer(file);
}

let input = document.getElementById("input-file"),
    info = document.getElementById("info");

input.addEventListener("change", function(event) {
  let file = input.files[0];
  
  if (file) {
    calculateHash(file, function(file_sha1) {
      info.textContent = file_sha1;
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-sha1/0.6.0/sha1.min.js"></script>

<input id="input-file" type="file">
<div id="info"></div>

需要js-sha1 (npm install js-sha1)。

归功于:How to checksum the file to be uploaded with javascript?

【讨论】:

  • 你能解释一下在这里做什么:reader.onload = function(event) { var contents = event.target.result; // 在这里散列你的内容... info.textContent = contents; }
  • “我想从浏览器中的数据 url 得到相同的校验和结果”——我的回答是:不要使用数据 URL,而是使用文件内容在浏览器中获取校验和。您需要在评论所在的位置插入 sha1 hashsum 生成器,散列 content。
  • 难道 event.target.result 和 data url 一样吗?使用文件内容是什么意思...我应该使用文件 blob 的哪个部分...对不起,但我是初学者
  • "Run code sn-p" 不适用于此 Github 链接。考虑在此处使用 CDN。
  • @denis.peplin 感谢您告诉我,它现在应该可以再次使用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-20
  • 2021-12-19
  • 2019-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多