49. Hash files

Hashing a file is relatively easy in C#. The following CalculateMD5 method calculates an MD5 hash code for a file:

// Return a file's MD5 hash.
public static string CalculateMD5(string filename)
{
// Make an MD5 hashing object.
using (MD5 md5 = MD5.Create())
{
// Open the file and pass the stream into the MD5 object.
using (FileStream stream = File.OpenRead(filename))
{
byte[] hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash);
}
}
}

This method first creates an MD5 object.

The MD5 class is one of several .NET Framework classes that represent hashing algorithms. Other hashing classes work with different hashing algorithms such as MD160, SHA1, SHA256, SHA384, SHA512, HMAC, and HMACtripleDES. You can use any of the hashing algorithms as long as you use the same algorithm when you hash a file and later validate its hash code.

The code then opens a stream to the file that you want to hash. It calls the MD5 object's ComputeHash method, passing it the file stream. The result is a byte array. The method finishes by using BitConverter.ToString to convert the array into a string with a format similar to F6-72-E5-7E-2E-09-6B-1A-9E-CE-9C-DE-F8-AE-13-98 and returns that as its result.

Download the HashFiles example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.55.18