How do I do a SHA1 File Checksum in C#?

Firesteel picture Firesteel · Jan 3, 2010 · Viewed 46.6k times · Source

How do I use the SHA1CryptoServiceProvider() on a file to create a SHA1 Checksum of the file?

Answer

user153498 picture user153498 · Jan 3, 2010
using (FileStream fs = new FileStream(@"C:\file\location", FileMode.Open))
using (BufferedStream bs = new BufferedStream(fs))
{
    using (SHA1Managed sha1 = new SHA1Managed())
    {
        byte[] hash = sha1.ComputeHash(bs);
        StringBuilder formatted = new StringBuilder(2 * hash.Length);
        foreach (byte b in hash)
        {
            formatted.AppendFormat("{0:X2}", b);
        }
    }
}

formatted contains the string representation of the SHA-1 hash. Also, by using a FileStream instead of a byte buffer, ComputeHash computes the hash in chunks, so you don't have to load the entire file in one go, which is helpful for large files.