【问题标题】:Node 'crypto' SHA256 hashing model behaving erratically节点“加密”SHA256 散列模型行为不规律
【发布时间】:2019-02-06 05:26:13
【问题描述】:

我有一个函数可以获取一个文件并找到它的 SHA256 哈希值。每次我重新提交文件时,它都会为同一个文件生成不同的哈希值。

在第一次提交时,它会产生正确的哈希值。每次重新提交都会产生一个不正确的哈希值。如果我以相同的顺序重新提交相同的文件,它们都会产生相同的(不正确的)哈希。

我认为缓冲区可能正在增加。或者也许是别的什么?我正在尝试弄清楚如何清除缓冲区数组。

有什么想法吗?

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;

【问题讨论】:

  • 一些上下文,好吗? (最好是minimal reproducible example,如果你能生产的话。)什么叫onChange 函数?从名称来看,我认为它可能会在文件更改时被调用,因此每次哈希都会不同也就不足为奇了。为什么,具体来说,你认为它有时是错误的?
  • 要么文件在重新加载时被更改,要么 reader.readAsArrayBuffer(files[0]) 每次返回为不同的文件。
  • 谢谢,将使用完整的反应组件代码进行编辑。
  • 我做了console.log(files[0]) 并且每次都返回具有不同哈希的完全相同的文件对象。
  • 不确定您是否仍然感兴趣,但我认为这可能与缓冲区数组“构建”多个文件有关。我在原帖中添加了一些额外的内容。

标签: node.js reactjs hash node-crypto


【解决方案1】:

您只创建了一次哈希 (const hash ...),然后每次页面更改为 hash.update(...) 时都添加到同一个哈希中。这每次都会产生不同的哈希值。

字符串类比:

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

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

如果你每次都创建一个新的哈希值,它应该是一致的。

const hashOutput = crypto.createHash("sha256")
    .update(Buffer.from(e.target.result))
    .digest("hex");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多