行为异常的节点"crypto" SHA256哈希模型 [英] Node 'crypto' SHA256 hashing model behaving erratically

查看:122
本文介绍了行为异常的节点"crypto" SHA256哈希模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

有什么想法吗?

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;

推荐答案

您一次创建了一个哈希(const hash ...),但是每次您的页面使用hash.update(...)更改时,都会将其添加到相同的哈希中.每次都会产生不同的哈希值.

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.

类比字符串:

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");

这篇关于行为异常的节点"crypto" SHA256哈希模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆