简体   繁体   English

为什么使用crypto-js为不同的pdf文件获得相同的哈希值?

[英]Why do I get the same hash for different pdf files using crypto-js?

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.我上传了一个 pdf 文件并使用 crypto-js 从中创建了一个散列,但无论我上传哪个文件,我总是得到相同的散列。 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.我对 txt 文件有同样的问题,如果我从资产目录加载文件。 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.我使用 Angular 6。这是我的做法。

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.更新:这就是我在创建哈希之前记录 this.file 时得到的结果。

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.您可以使用FileReader读取文件并根据其内容创建哈希。

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] .虽然我不确定为什么它会生成相同的哈希,但我猜它与一些内部方法有关,例如toString()为任何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)" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM