MD5 is short for Message Digest Algorithm 5 (information Digest Algorithm). MD5 is a Hash technology that is widely used in encryption, decryption, Data signature, and data integrity verification. Any file, whether it is an executable program, image file, temporary file, or any other type of file, regardless of its size, can calculate an MD5 value, if the file is modified, its MD5 value will be completely different even if only one byte is modified. Therefore, we can verify whether the file has been "Tampered" by comparing the MD5 value of the same file. C # the MD5 value of the file can be conveniently calculated:
Calculate the MD5 value of a file
/// <Summary>
/// Calculate the MD5 value of the file
/// </Summary>
/// <Param name = "fileName"> name and path of the file to calculate the MD5 value </param>
/// <Returns> the MD5 value is a hexadecimal string </returns>
Public static string MD5File (string fileName)
{
Return HashFile (fileName, "md5 ");
}
/// <Summary>
/// Calculate the file hash value
/// </Summary>
/// <Param name = "fileName"> name and path of the file to calculate the hash value </param>
/// <Param name = "algName"> algorithm: sha1, md5 </param>
/// <Returns> hash value hexadecimal string </returns>
Public static string HashFile (string fileName, string algName)
{
If (! System. IO. File. Exists (fileName ))
Return string. Empty;
FileStream fs = new FileStream (fileName, FileMode. Open, FileAccess. Read );
Byte [] hashBytes = HashData (fs, algName );
Fs. Close ();
Return ByteArrayToHexString (hashBytes );
}
/// <Summary>
/// Calculate the hash value
/// </Summary>
/// <Param name = "stream"> Stream to calculate the hash value </param>
/// <Param name = "algName"> algorithm: sha1, md5 </param>
/// <Returns> hash value byte array </returns>
Public static byte