Different sha1 hashes calculated in PHP vs Node.js

591 views Asked by At

Any ideas why the following snippets of code generate different hash values? I'm concatenating the contents of a file and the filename before generating the hash. My goal is to make the Node code generate the same sha1 hash as the PHP code below.

PHP code:

$filename = 'picture.jpg';
$filecontent = file_get_contents($filename);
$hash = sha1($filecontent.$filename);
print "PHP  hash:$hash\n";

Node Code:

var co = require('co');
var cofs = require('co-fs');

var filename = 'picture.jpg';
co(function*(){
  var filecontent = yield cofs.readFile(filename);
  var hash = require('crypto').createHash('sha1').update(filecontent+filename).digest('hex');
  console.log('node hash:'+hash);
});

Also, a quick note is that the hashes are generated the same when I do not concatenate the filename to filecontent.

1

There are 1 answers

1
Sukanta K. Hazra On BEST ANSWER

readFile returns a buffer object which you are trying to concatenate to a string filename. You need to extend the filecontent buffer with the filename. You can use buffertools for this.

"use strict";
var co = require('co');
var cofs = require('co-fs');
var buffertools = require('buffertools');

var filename = 'picture.jpg';
co(function*(){
  var filecontent = yield cofs.readFile(filename);
  var hash = require('crypto').createHash('sha1').update(buffertools.concat(filecontent, filename)).digest('hex');
  console.log('node hash:'+hash);
}).catch(function(err) {
  console.log(err);
})