There might be situations when you might want to quickly calculate the MD5 or SHA2 values of any file or a set of files. The solution depends on what is your requirement: 1) Its a one time work and you would just want the results in a text / html file 2) You want the hash inside your .Net program
Scenario 1: The best bet is to download a program called HashMyFiles by nirsoft.net
This nifty little program can generate an HTML report containing the hashes of all the files in the specified file/folder.
Scenario 2: Here is the C# version of creating the hashes using the build in Cryptography classes.
using System.Security.Cryptography;
using System.Text;
public string GetMD5(string filePath)
{
StringBuilder sb = new StringBuilder();
FileStream fs = new FileStream(file, FileMode.Open);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] hash = md5.ComputeHash(fs);
fs.Close();
fs.Dispose();
foreach (byte hex in hash)
{
//Returns hash in lower case.
//To return upper case change “x2″ to “X2″
sb.Append(hex.ToString(”x2″));
}
return sb.ToString();
}
public string GetSHA2(string filePath)
{
StringBuilder sb = new StringBuilder();
FileStream fs = new FileStream(file, FileMode.Open);
SHA256 s2 = new SHA256CryptoServiceProvider();
byte[] hash = s2.ComputeHash(fs);
fs.Close();
fs.Dispose();
foreach (byte hex in hash)
{
//Returns hash in lower case.
//To return upper case change “x2″ to “X2″
sb.Append(hex.ToString(”x2″));
}
return sb.ToString();
}