C # example of calculating the MD5 value of a file

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.