0

我试图弄清楚为什么在通过sha1算法运行字符串时我没有得到相同的哈希值。

请考虑以下结果:

echo moosecodes | shasum
538f5d940a8f1aeabde1d5c6da4ebae1230ba5da  -

echo -n moosecodes | shasum  
c09129372713d1c7005f4aa1d50bf598912c473a  -

temp.txt包含moosecodes没有换行的字符串,但是当从文件中回显字符串时,哈希值不同:

echo temp.txt | shasum
c3ec5f2c30a4198dc4e0323101441da0bcdd2aa9  -

echo -n temp.txt | shasum
45ebed19db9cfb3cea503d6b62a50ffe6b30247c  -

谁能向我解释为什么会这样?起初我认为这与文件附加了元数据这一事实有关,但在这种情况下,我只是将其内容回显到哈希器,所以它不会与前两个相同我在上面展示的例子?

4

1 回答 1

2

你在跑步echo temp.txt | shasum,不是cat temp.txt | shasumshasum < temp.txt。您没有测试文件内容的 shasum,而是temp.txt意外地使用shasum了字符串“temp.txt”。

# Your first example
$ echo moosecodes | shasum
538f5d940a8f1aeabde1d5c6da4ebae1230ba5da *-
$ echo -n moosecodes | shasum
c09129372713d1c7005f4aa1d50bf598912c473a *-

# Now prepare the file...
$ echo -n moosecodes > temp.txt

# But accidentally take the shasum of the string "temp.txt",
# with or without the newline.
$ echo temp.txt | shasum
c3ec5f2c30a4198dc4e0323101441da0bcdd2aa9 *-
$ echo -n temp.txt | shasum
45ebed19db9cfb3cea503d6b62a50ffe6b30247c *-

# However, you can use the "cat" command to pipe the text...
$ cat temp.txt | shasum
c09129372713d1c7005f4aa1d50bf598912c473a *-
# Or properly redirect from a file using < ...
$ shasum < temp.txt
c09129372713d1c7005f4aa1d50bf598912c473a *-
# Or even just pass the filename into shasum directly.
$ shasum temp.txt
c09129372713d1c7005f4aa1d50bf598912c473a *temp.txt
于 2018-08-06T21:18:45.953 回答