PHP与Node.js中计算的不同sha1哈希

PHP与Node.js中计算的不同sha1哈希,php,node.js,sha1,Php,Node.js,Sha1,你知道为什么下面的代码片段会生成不同的散列值吗?在生成哈希之前,我将连接文件内容和文件名。我的目标是使节点代码生成与下面的PHP代码相同的sha1哈希 PHP代码: $filename = 'picture.jpg'; $filecontent = file_get_contents($filename); $hash = sha1($filecontent.$filename); print "PHP hash:$hash\n"; 节点代码: var co = require('co');

你知道为什么下面的代码片段会生成不同的散列值吗?在生成哈希之前,我将连接文件内容和文件名。我的目标是使节点代码生成与下面的PHP代码相同的sha1哈希

PHP代码:

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

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

另外,需要注意的是,当我没有将文件名连接到filecontent时,哈希值的生成是相同的。

readFile返回一个缓冲区对象,您试图将其连接到字符串文件名。您需要使用文件名扩展filecontent缓冲区。您可以使用buffertools进行此操作

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

readFile返回一个缓冲区对象,您试图将其连接到字符串文件名。您需要使用文件名扩展filecontent缓冲区。您可以使用buffertools进行此操作

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

查找处理数据(文件名)之间的差异。查找处理数据(文件名)之间的差异。查找处理数据(文件名)之间的差异。太棒了,谢谢!这一行也可以工作:var hash=require('crypto').createHash('sha1').update(Buffer.concat([filecontent,newbuffer(filename)]).digest('hex');log('node hash:'+hash);太棒了,谢谢!这一行也可以工作:var hash=require('crypto').createHash('sha1').update(Buffer.concat([filecontent,newbuffer(filename)]).digest('hex');log('node hash:'+hash);太棒了,谢谢!这一行也可以工作:var hash=require('crypto').createHash('sha1').update(Buffer.concat([filecontent,newbuffer(filename)]).digest('hex');log('node hash:'+hash);