Thursday, January 6, 2011

MD5 Hash

To generate an MD5 like 9adff06850bedeace9d0c6ebfe7ce507

private byte[] GetData(string filePath, string fileName, out string md5)
{
string path = Path.Combine(filePath, fileName);

byte[] bytes = System.IO.File.ReadAllBytes(path);

md5 = GetHash(bytes);

return bytes;
}

private string GetHash(byte[] data)
{
byte[] bytes = System.Security.Cryptography.MD5.Create().ComputeHash(data);

return StringifyMD5(bytes); // This method will return something like 9adff06850bedeace9d0c6ebfe7ce507
}

private string StringifyMD5(IEnumerable< byte> bytes)
{
var result = new StringBuilder();

foreach (byte b in bytes)
{
result.AppendFormat("{0:x2}", b);
}

return result.ToString();
}

we can also use it to generate a hash based on a string, for example, a filename:

string fileName = "some_file_name.xml";
string hash = GetHash(System.Text.Encoding.UTF8.GetBytes(fileName));

No comments: