digest returns the same value with different data

advertisements

I'm using Javascript Forge to get a digest for some data, right now the experiment is with different documents and the following lines of code always returns the same hash:

function obtainData() {
    getDocument(getHash);
}

function getDocument(callback) {
    var file = dInput.files[0];
    var reader = new FileReader();
    reader.onload = function(e){
        var contents = e.target.result;
        var array = callback(contents)
        console.log(array.digest().toHex());
    }
    reader.readAsArrayBuffer(file);
}

function getHash(buffer) {
    digestHash = forge.md.sha256.create();
    digestHash.update(buffer);
    //always the same with different bytes everytime
    console.log(digestHash.digest().toHex());
    return digestHash;
}

why is this happening? Am I missing something?

Tried with different browsers and still the same digestHash value


Forge library usually works with Uint8. converting content to Uint8Array should works properly

reader.onload = function(e){
    var contents = e.target.result;
    var  binary = arrayBufferToString(contents);
    var array = callback(binary)
    console.log(array.digest().toHex());
}

function arrayBufferToString( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return binary;
}

Using WebCryptographiApi is also a good solution

function obtainData() {
  getDocument(getHash);
}

function arrayBufferToString( buffer ) {
  var binary = '';
  var bytes = new Uint8Array( buffer );
  var len = bytes.byteLength;
  for (var i = 0; i < len; i++) {
    binary += String.fromCharCode( bytes[ i ] );
  }
  return binary;
}

function getDocument(callback) {
  var file = dInput.files[0];
  var reader = new FileReader();
  reader.onload = function(e){
    var contents = e.target.result;
    var array = callback(contents)
    console.log(array.digest().toHex());
  }
  reader.readAsArrayBuffer(file);
}

function getHash(buffer) {
  digestHash = forge.md.sha256.create();
  digestHash.update(arrayBufferToString(buffer));
  return digestHash;
}
<script src="https://cdn.rawgit.com/artjomb/96b970358e20410fa64daa2e844aeb0f/raw/5375e7171ef297d436d65b962149dcc0e1960b2b/forge_v0.6.39.min.js"></script>
<input id="dInput" type="file">
<button onclick="obtainData()">hash</button>