how would I perform a SHA1 hash on a file?

一笑奈何 提交于 2019-11-29 21:06:36

问题


If I have a file that I want to monitor for any changes (other than looking at the file date stamps etc).

How could I perform a SHA1 hash on its contents?

I think this is what GIT does, so I just want to learn how to do it


回答1:


using (FileStream stream = File.OpenRead(@"C:\File.ext"))
{
    using (SHA1Managed sha = new SHA1Managed())
    {
        byte[] checksum = sha.ComputeHash(stream);
        string sendCheckSum = BitConverter.ToString(checksum)
            .Replace("-", string.Empty);
    }
}

Calculate the checksum periodically.




回答2:


For the specific application that you described, finding the SHA-1 hash of each file in the directory and then XORing them together would work well.

byte[] checksum = new byte[sha1Length];
for each file
   for (int index = 0; index < sha1Length; index++)
       checksum[index] ^= fileChecksum[index]

Edited to Add: As pointed out in the comments, this won't really work. One specific scenerio would be adding two identical files, which would cancel each other out in the XOR. Perhaps creating a stream with all the file names and timestamps and file hashes and then hashing that would give you what you need.

Edited again: OK, now you've changed your question! So nevermind!



来源:https://stackoverflow.com/questions/1969977/how-would-i-perform-a-sha1-hash-on-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!