1
var crypto = require('crypto');
var fs = require('fs');
var file1 = process.argv[2];
var file2 = process.argv[3];

var sha1sum = function(input){
    return crypto.createHash('sha1').update(JSON.stringify(input)).digest('hex')
};

var first = sha1sum(file1);
var second = sha1sum(file2);

console.log(first + '  ' + file1);
console.log(second + '  ' + file2);
if (first == second) {
    console.log("the two hashes are equal");
} else {
    console.log("the two hashes aren't equal");
}

The above is the current code I'm using. It takes in two file inputs and compares their hashes. However, when passing the same file from two different locations as arguments, they have different sha1 hashes. Is this supposed to happen, or is my code incorrect?

  • 5
    You appear to be hashing the file *names*, not the contents of the files. – Greg Hewgill Jun 16 '15 at 19:32
  • Shoot... I want to create a hash from the name and the content. How would I go about doing that? –  Jun 16 '15 at 19:38
  • 1
    You might want to investigate related questions such as [read txt file using node.js?](https://stackoverflow.com/questions/9168737/read-txt-file-using-node-js) – Greg Hewgill Jun 16 '15 at 19:49
  • Awesome! Thanks for the heads up :) –  Jun 16 '15 at 20:02
  • Also you most likely don't want to load the whole file into memory but rather digest your file line by line, thus calling `update(line)` multiple times instead of wrapping it all up into your `sha1sum` function. – Sebastian S Jul 09 '15 at 08:34
  • I'm probably thinking about this wrong because I'm fairly new to programming, but how would I take the sha1 of the whole thing if I only had a line of the entire thing in memory at any time? Wouldn't I have to have the entire content stored before I could sha1 it? –  Jul 10 '15 at 14:46

1 Answers1

1

So, it comes down to what you're hashing.

As was pointed out, I was only hashing the name. If you're only hashing the file contents, the sha1 values will be the same. However, if you combine the address value and the sha1 value, you will have distinct sha1s when comparing the same file in two different locations. Whether or not the sha1 value is location agnostic depends entirely on what you're passing into the sha1 value.