0

I have a function that takes a file and finds its SHA256 hash. Each time I resubmit a file, it produces a different hash for the same file.

On the first submission, it produces the correct hash. Each re-submission produces an incorrect hash. If I re-submit the same files in the same order, they all produce the same (incorrect) hash.

I think that the buffer might be building up. Or maybe something else? I'm trying to figure out how to clear the buffer array.

Any ideas?

import React, { Component } from "react";

const crypto = require("crypto");
const hash = crypto.createHash("sha256");

class SearchPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hashOutput: "",
      fileName: "",
    };
  }

  onChange(e) {
    let files = e.target.files;
    this.setState({ fileName: files[0].name });
    let reader = new FileReader();
    reader.readAsArrayBuffer(files[0]);

    reader.onload = e => {
      hash.update(Buffer.from(e.target.result));
      const hashOutput = hash.digest("hex");
      this.setState({ hashOutput });
      console.log(hashOutput);
    };
  }

  render() {
    return (
        <div onSubmit={this.onFormSubmit}>
          <input type="file" name="file" onChange={e => this.onChange(e)} />
        </div>
    );
  }
}

export default SearchPage;
Hanley Soilsmith
  • 579
  • 2
  • 9
  • 27
  • 1
    Some context, please? (Preferably a [mcve], if you can produce one.) What's calling that `onChange` function? From the name, I assume it's probably called whenever the file changes, so it's hardly a surprise that the hash will be different every time. Why, specifically, do you think it's sometimes wrong? – Ilmari Karonen Feb 06 '19 at 05:31
  • Either the file is changed when re-loaded or reader.readAsArrayBuffer(files[0]) return as different file every time. – Roshith Feb 06 '19 at 05:32
  • Thanks, will edit with the full react component code. – Hanley Soilsmith Feb 06 '19 at 05:33
  • I did `console.log(files[0])` and am returning the exact same file object with a different hash each time. – Hanley Soilsmith Feb 06 '19 at 05:46
  • Not sure if ya'll are still interested, but I think it might have to do with the buffer array "building up" multiple files. I added some extra content to the original post. – Hanley Soilsmith Feb 06 '19 at 06:18

1 Answers1

1

You're creating a hash once (const hash ...) but then adding to that same hash every time your page changes with hash.update(...). This will produce a different hash every time.

An analogy with strings:

var s = "";
onChange(e) {
    s = s + "data";
    console.log(s);
}

// Output on first load: data
// Output on secnd load: datadata
// etc

If you create a fresh hash each time it should be consistent.

const hashOutput = crypto.createHash("sha256")
    .update(Buffer.from(e.target.result))
    .digest("hex");
Tom
  • 6,946
  • 2
  • 47
  • 63