Posts tagged ‘md5’
Compute MD5 checksum in hex string
Recently I need to validate the checksum of the downloaded data file. After looking around, I find this reference to teach you how to compute the MD5 hash, http://www.nikhedonia.com/notebook/entry/verifying-md5-checksum/. However i found that the MD5 hash in the checksum file stores as 32-characters, which is different from 16-bytes MD5 hash. Finally I knew that this 32-characters string is the hex string of the 16 bytes MD5 values. Therefore i have made some modifications and below is my code for your reference:
public string ComputeMd5HashFromFile(string filePath)
{
StreamReader fileReader = null;
UTF8Encoding utf8Encoding = new System.Text.UTF8Encoding();
StringBuilder result = new StringBuilder(32);
byte[] hash = null;
try
{
fileReader = File.OpenText(filePath);
MD5 md5 = new MD5CryptoServiceProvider();
hash = md5.ComputeHash(utf8Encoding.GetBytes(fileReader.ReadToEnd()));
foreach (byte b in hash)
{
result.Append(b.ToString("x2").ToUpper()); // used to convert each byte to a hex string
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (fileReader != null) fileReader.Close();
}
return result.ToString().ToUpper();
}