views:

915

answers:

2

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

+3  A: 

With the ComputeHash method. See here:

ComputeHash

Example snippet:

string hash = BitConverter.ToString((new SHA1CryptoServiceProvider()).ComputeHash(buffer));

Where buffer is the contents of your file.

byte
+6  A: 
FileStream fs = new FileStream(@"C:\file\location", FileMode.Open);
using (SHA1Managed sha1 = new SHA1Managed())
{
    byte[] hash = sha1.ComputeHash(fs);
    string formatted = string.Empty;
    foreach (byte b in hash)
    {
         formatted += b.ToString("X2");
    }
}

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.

nasufara