开发者

how would I perform a SHA1 hash on a file?

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


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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜