Reputation: 629
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;
Upvotes: 0
Views: 247
Reputation: 7804
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");
Upvotes: 1