I upload a pdf file and use crypto-js to create a hash from it, but I always get the same hash no matter which file I upload. Also, the hash I get does not correspond to the hash I get from the file when I use an online tool to create the hash. I have the same issue with txt files and if I load the files from the assets directory. I also tried other libraries and have the same issue.
What I'm I missing?
I use Angular 6. Here is how I do it.
import { Component } from '@angular/core';
import sha256 from 'crypto-js/sha256';
@Component({
selector: 'ct-sign-page',
templateUrl: './sign-page.component.html',
styles: []
})
export class SignPageComponent {
public file: File;
public fileChange(event): void {
this.file = event.target.files[0];
const hash = sha256(this.file);
console.log(hash.toString());
}
}
Update: This is what I get if I log this.file before I create the hash.
File
lastModified: 1603727900290
lastModifiedDate: Mon Oct 26 2020 16:58:20 GMT+0100 (Central European Standard Time) {}
name: "sample.pdf"
size: 3028
type: "application/pdf"
webkitRelativePath: ""
__proto__: File
You can use FileReader
to read the file and create a hash based on its content.
Though I'm not sure why it is generating the same hash but I guess it is related to some internal methods like toString()
which return same string for any event.target.files[0]
.
fileChange = (event) => {
var file = event.target.files[0];
const fileReader = new FileReader();
fileReader.addEventListener('loadend', (evt) => {
if (evt.target.readyState == FileReader.DONE) {
const hash = CryptoJS.SHA256(fileReader.result);
console.log(hash.toString());
}
});
fileReader.readAsDataURL(file);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
<input type="file" #fileInput onchange="fileChange(event)" />