简体   繁体   English

git shasum和node sha1不会产生相同的哈希值

[英]git shasum and node sha1 do not produce the same hashe

$ echo -e 'blob 14\0Hello, World!' | shasum

produces: 8ab686eafeb1f44702738c8b0f24f2567c36da6d 产生: 8ab686eafeb1f44702738c8b0f24f2567c36da6d

running this in js/node: 在js / node中运行它:

var sha1 = require('sha1');

const fileContents = "Hello, World!";
const length = fileContents.length + 1;

const blobString = `blob ${length}\0${fileContents}`;

const hash = sha1(blobString);

console.log(blobString);
console.log(hash);

produces: 产生:

blob 14Hello, World!
d4fcfe4d339d4e59d168fdf3c0ad445fa980a7d6

why are the hashes not equal ? 为什么哈希值不相等? ( 8ab686eafeb1f44702738c8b0f24f2567c36da6d != d4fcfe4d339d4e59d168fdf3c0ad445fa980a7d6 ) 8ab686eafeb1f44702738c8b0f24f2567c36da6d != d4fcfe4d339d4e59d168fdf3c0ad445fa980a7d6

The hashes are not equal because of the difference of a newline character in the input. 由于输入中换行符的不同,因此哈希值不相等。 echo adds a newline. echo添加换行符。 Use printf instead: 使用printf代替:

printf 'blob 14\0Hello, World!' | shasum
# prints: d4fcfe4d339d4e59d168fdf3c0ad445fa980a7d6

This works too, but not as portable, because the flags of echo are not supported predictably in all systems: 这也可行,但不那么可移植,因为并非所有系统都可预测地支持echo标志:

echo -ne 'blob 14\0Hello, World!' | shasum

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

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