how would I perform a SHA1 hash on a file?

后端 未结 2 364
囚心锁ツ
囚心锁ツ 2021-01-03 02:04

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?

相关标签:
2条回答
  • 2021-01-03 02:52

    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 讨论(0)
  • 2021-01-03 03:01
    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.

    0 讨论(0)
提交回复
热议问题