I need to calculate the Hash of the Contents of a File in C#? So, that I can compare two file hashes in my app. I have search but not found.
A hash is a one-way digest function. It takes a number of input bytes and computes a fixed-length value from it. If you compute the same hash again, you get the same result. Generally the numeric value of the length of the input is not considered, as the data is inherently changed if you change the length.
With modular hashing, the hash function is simply h(k) = k mod m for some m (usually, the number of buckets). The value k is an integer hash code generated from the key. If m is a power of two (i.e., m=2p), then h(k) is just the p lowest-order bits of k.
A Hash Table in C/C++ (Associative array) is a data structure that maps keys to values. This uses a hash function to compute indexes for a key. Based on the Hash Table index, we can store the value at the appropriate location.
A hash value is a numeric value of a fixed length that uniquely identifies data. Hash values represent large amounts of data as much smaller numeric values, so they are used with digital signatures. You can sign a hash value more efficiently than signing the larger value.
You could use MD5CryptoServiceProvider
, which will work with text based files as well as binary files.
byte[] myFileData = File.ReadAllBytes(myFileName);
byte[] myHash = MD5.Create().ComputeHash(myFileData);
Or... if you work with large files and do not want to load the whole file into memory:
byte[] myHash;
using (var md5 = MD5.Create())
using (var stream = File.OpenRead(myFileName))
myHash = md5.ComputeHash(stream);
You can compare to byte arrays from two files with Enumerable.SequenceEqual
:
myHash1.SequenceEqual(myHash2);
You could also try to create an CRC-calculator. See: http://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net
You should search better ;)
using System.IO;
using System.Text;
using System.Security.Cryptography;
protected string GetMD5HashFromFile(string fileName)
{
FileStream file = new FileStream(fileName, FileMode.Open);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file);
file.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
Pass your file to this function like this.
GetMD5HashFromFile("text1.txt");
GetMD5HashFromFile("text2.txt");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With