javascript - git shasum 和 Node sha1 不产生相同的哈希值

标签 javascript node.js git md5 sha

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

产生:8ab686eafeb1f44702738c8b0f24f2567c36da6d

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

产生:

blob 14Hello, World!
d4fcfe4d339d4e59d168fdf3c0ad445fa980a7d6

为什么哈希值不相等? (8ab686eafeb1f44702738c8b0f24f2567c36da6d!= d4fcfe4d339d4e59d168fdf3c0ad445fa980a7d6)

最佳答案

由于输入中换行符的不同,哈希值不相等。 echo 添加换行符。使用 printf 代替:

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

这也有效,但不那么可移植,因为并非所有系统都支持 echo 标志:

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

关于javascript - git shasum 和 Node sha1 不产生相同的哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47728891/

相关文章:

javascript - $.getJSON 函数在其他所有操作之后执行

javascript - 使用 document.write 编写 HTML 导致尝试嵌入 YouTube 时出错

javascript - 这个嵌套的 jQuery 命令如何正确编写?

node.js - Sequelize、findAll、属性不能重命名列

node.js - 使用 gulp 仅运行一个 mocha 测试文件

linux - git pull/push 返回 : fatal: protocol error: bad line length character: _

javascript - 这两个 javascript 和 jquery 语句有什么区别?

javascript - Express js Controller 从 api 服务获取数据并呈现 View

git - 使用 Visual Studio 2017 克隆 TFS Git 存储库时出现错误 400

java - 使用 Hawtio 时的 org.eclipse.jgit.errors.LockFailedException