简体   繁体   English

用PHP vs Node.js计算的不同sha1哈希

[英]Different sha1 hashes calculated in PHP vs Node.js

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. 我的目标是使Node代码生成与下面的PHP代码相同的sha1哈希。

PHP code: PHP代码:

$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. 另外,需要快速注意的是,当我不将文件名连接到filecontent时,散列的生成方式相同。

readFile returns a buffer object which you are trying to concatenate to a string filename. readFile返回一个缓冲区对象,您尝试将其连接到字符串文件名。 You need to extend the filecontent buffer with the filename. 您需要使用文件名扩展filecontent缓冲区。 You can use buffertools for this. 您可以为此使用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);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM