Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistent Buffer SHA1 in Node.js #15

Open
andraaspar opened this issue Jun 17, 2020 · 2 comments
Open

Inconsistent Buffer SHA1 in Node.js #15

andraaspar opened this issue Jun 17, 2020 · 2 comments

Comments

@andraaspar
Copy link

I have a foo.txt like this:

foo
bar
baz

(LF. No LF at the end.)

And I have the following script:

const { sha1 } = require("crypto-hash");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");

main();

async function main() {
  const filePath = "foo.txt";
  const buf = fs.readFileSync(filePath);
  const str = fs.readFileSync(filePath, {
    encoding: "utf8",
  });
  console.log(await sha1(buf));
  console.log(await sha1(str));
  console.log(
    await new Promise((resolve, reject) => {
      const hash = crypto.createHash("sha1");
      const input = fs.createReadStream(filePath);
      input.on("readable", () => {
        const data = input.read();
        if (data) {
          hash.update(data);
        } else {
          resolve(hash.digest("hex"));
        }
      });
    })
  );
}

When I run it 3 times I get:

PS C:\Temp> node .\hashtest.js
4c37dbe6f4897fbed62502239273902421e1ea6a
01e06a68df2f0598042449c4088842bb4e92ca75
01e06a68df2f0598042449c4088842bb4e92ca75
PS C:\Temp> node .\hashtest.js
678082bb5b423c3dec7eb593465bd2d2cfa54287
01e06a68df2f0598042449c4088842bb4e92ca75
01e06a68df2f0598042449c4088842bb4e92ca75
PS C:\Temp> node .\hashtest.js
35d9940f295a0205252456e8c808eb5f651711b1
01e06a68df2f0598042449c4088842bb4e92ca75
01e06a68df2f0598042449c4088842bb4e92ca75

The output of sha1(buf) seems to constantly change, and never match the expected result.

@andraaspar
Copy link
Author

Node: 12.14.1
crypto-hash: 1.2.2

@andraaspar
Copy link
Author

Also, this:

  console.log(
    await new Promise((resolve, reject) => {
      const hash = crypto.createHash("sha1");
      hash.update(buf);
      resolve(hash.digest("hex"));
    })
  );

Produces the correct result (like the latter two).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant