Hash large files with crypto.subtle.digest(“SHA-256”, buffer)

青春壹個敷衍的年華 提交于 2021-02-11 07:18:25

问题


i have developed a web application where a user can select multiple files via a input field. Then the sha-256 checksums are calculated by the following code. The code (taken from developer.mozilla.org) only works for small files. What do I have to change to handle large files (e.g. 1GB+) too?

function sha256(buffer){
  return crypto.subtle.digest("SHA-256", buffer).then(function (hash) {
    return hex(hash);
  });
}

function hex(buffer) {
  var hexCodes = [];
  var view = new DataView(buffer);
  for (var i = 0; i < view.byteLength; i += 4) {
    // Using getUint32 reduces the number of iterations needed (we process 4 bytes each time)
    var value = view.getUint32(i)
    // toString(16) will give the hex representation of the number without padding
    var stringValue = value.toString(16)
    // We use concatenation and slice for padding
    var padding = '00000000'
    var paddedValue = (padding + stringValue).slice(-padding.length)
    hexCodes.push(paddedValue);
  }

  // Join all the hex strings into one
  return hexCodes.join("");
}

来源:https://stackoverflow.com/questions/52738019/hash-large-files-with-crypto-subtle-digestsha-256-buffer

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