为什么git散列对象返回与openssl sha1不同的散列? [英] Why does git hash-object return a different hash than openssl sha1?

查看:120
本文介绍了为什么git散列对象返回与openssl sha1不同的散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:我下载了从code.google到我的Macbook Pro(Mac OS X 10.6.6)。



我想要验证该特定文件的校验和发布为862456662a11e2f386ff0b24fdabcb4f6c1c446a(SHA-1)。 git hash-object 给了我一个不同的散列,但是 openssl sha1 返回了预期的862456662a11e2f386ff0b24fdabcb4f6c1c446a。



以下实验似乎排除了任何可能的下载损坏或换行符差异,并指出实际上存在两种不同的算法:

  $ echo A> foo.txt 
$ cat foo.txt
A
$ git hash-object foo.txt
f70f10e4db19068f79bc43844b49f3eece45c4e8
$ openssl sha1 foo.txt
SHA1( foo.txt)= 7d157d7c000ae27db146575c08ce30df893d3a64

发生了什么?

git hash-object 不仅仅是对文件中的字节进行散列 - 你可以看到不同之处:它在字符串前面加上字符串blob,后面跟着文件大小,在文件内容散列前加上NUL。在堆栈溢出的其他答案中有更多的细节:



或者,为了说服自己,请尝试如下所示:

  $ echo -n hello | git hash-object --stdin 
b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0

$ printf'blob 5\0hello'> test.txt
$ openssl sha1 test.txt
SHA1(test.txt)= b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0


Context: I downloaded a file (Audirvana 0.7.1.zip) from code.google to my Macbook Pro (Mac OS X 10.6.6).

I wanted to verify the checksum, which for that particular file is posted as 862456662a11e2f386ff0b24fdabcb4f6c1c446a (SHA-1). git hash-object gave me a different hash, but openssl sha1 returned the expected 862456662a11e2f386ff0b24fdabcb4f6c1c446a.

The following experiment seems to rule out any possible download corruption or newline differences and to indicate that there are actually two different algorithms at play:

$ echo A > foo.txt
$ cat foo.txt
A
$ git hash-object foo.txt 
f70f10e4db19068f79bc43844b49f3eece45c4e8
$ openssl sha1 foo.txt 
SHA1(foo.txt)= 7d157d7c000ae27db146575c08ce30df893d3a64

What's going on?

解决方案

You see a difference because git hash-object doesn't just take a hash of the bytes in the file - it prepends the string "blob " followed by the file size and a NUL to the file's contents before hashing. There are more details in this other answer on Stack Overflow:

Or, to convince yourself, try something like:

$ echo -n hello | git hash-object --stdin
b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0

$ printf 'blob 5\0hello' > test.txt
$ openssl sha1 test.txt
SHA1(test.txt)= b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0

这篇关于为什么git散列对象返回与openssl sha1不同的散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆