Hash Functions
There are times when it is handy to have a file hash to ensure File Integrity or simply for automated submission to databases like VirusTotal. Below is example POC code to generate MDF and SHA hashes using the Microsoft System.Security.Cryptography library. With minor tweaks and a salt, these methods could also be used to generate one way string hashes for use in other applications.
Create MD5 Hash
/// <summary>
/// GetMD5 accepts a string variable representing the path and file to be hashed.
/// returns the hashed value.
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
string GetMD5(string sFileName)
{
//declare the variable to hold our output
string sHash = "";
//generate an instance of the MD5 crypto class. By using the "using" statement the object
//will be cleaned up when we are done with it.
using (var md5 = MD5.Create())
{
using (var thefileStream = File.OpenRead(sFileName))
{
//ComputeHash() returns a byteArray
var vHash = md5.ComputeHash(thefileStream);
//convert the byte[] to a readable string
sHash = BitConverter.ToString(vHash).Replace("-", String.Empty).ToLower();
}
}
return sHash;
}
Create SHA256 Hash
/// <summary>
/// GetSHA accepts a string variable representing the path and file to be hashed.
/// returns the hashed value.
/// </summary>
/// <param name="sfileName"></param>
/// <returns></returns>
string GetSHA(string sFileName)
{
//declare the variable to hold our output
string sHash = "";
//generate an instance of the MD5 crypto class. By using the "using" statement the object
//will be cleaned up when we are done with it.
using (var sha256Hash = SHA256.Create())
{
// ComputeHash - returns byte array
using (var stream = File.OpenRead(sFileName))
{
var vHash = sha256Hash.ComputeHash(stream);
//convert the byte[] to a readable string
sHash = BitConverter.ToString(vHash).Replace("-", String.Empty).ToLower();
}
}
return sHash;
}