3

I am trying to read-in a file and calculate the SHA-256 hash. The code works on localhost perfectly fine (Chrome and Safari).

As soon as I upload the page on a webserver I will get the following error in Google Chrome:

Uncaught TypeError: Cannot read property 'digest' of undefined at FileReader.reader.onload (hashDocument.js:40)

However, the webpage works fine in Safari as well as on Android devices.

function convertStringToArrayBufferView(str)
{
    var bytes = new Uint8Array(str.length);
    for (var iii = 0; iii < str.length; iii++)
    {
        bytes[iii] = str.charCodeAt(iii);
    }
    return bytes;
}

function convertArrayBufferToHexaDecimal(buffer)
{
    var data_view = new DataView(buffer);
    var iii, len, hex = '', c;

    for(iii = 0, len = data_view.byteLength; iii < len; iii += 1)
    {
        c = data_view.getUint8(iii).toString(16);
        if(c.length < 2)
        {
            c = '0' + c;
        }
        hex += c;
    }
    return hex;
}

function hashIt() {
  var nBytes = 0,
      oFiles = document.getElementById("documentIn").files,
      nFiles = oFiles.length;
  for (var nFileId = 0; nFileId < nFiles; nFileId++) {
      //console.log(oFiles[nFileId]);

      var reader = new FileReader();

      reader.onload = function(e) {
      var text = reader.result;
      var promise = crypto.subtle.digest({name: "SHA-256"},   convertStringToArrayBufferView(text));

    promise.then(function(result){
      var hashValue = convertArrayBufferToHexaDecimal(result);
      // update input field
      console.log("hashValue");
      $("#documentHash").val(hashValue);
    });

};

reader.readAsText(oFiles[nFileId]);

    nBytes += oFiles[nFileId].size;
  }
}
Derawi
  • 430
  • 4
  • 12
  • 1
    In Chrome, some of the crypto methods/properties are available on https connection only, `crypto.subtle` is one of these. See https://stackoverflow.com/questions/46670556/how-to-enable-crypto-subtle-for-unsecure-origins-in-chrome – Teemu May 30 '18 at 07:42
  • Thanks good to have an explanation! Is there any workaround without serving https only? – Derawi May 30 '18 at 08:47
  • One possibility might be to use an alternative implementation of the algorithm. A little web searching suggests maybe https://github.com/emn178/js-sha256, but I can't vouch for it. – mwfearnley Jan 21 '19 at 11:10

0 Answers0