Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an MD5 hash digest from a text file?

Tags:

c#

hash

md5

Using C#, I want to create an MD5 hash of a text file. How can I accomplish this?

Update: Thanks to everyone for their help. I've finally settled upon the following code -

// Create an MD5 hash digest of a file
public string MD5HashFile(string fn)
{            
    byte[] hash = MD5.Create().ComputeHash(File.ReadAllBytes(fn));
    return BitConverter.ToString(hash).Replace("-", "");            
}
like image 503
Craig Schwarze Avatar asked Jan 27 '10 21:01

Craig Schwarze


People also ask

How do I get the MD5 hash of a file?

Type the following command: md5sum [type file name with extension here] [path of the file] -- NOTE: You can also drag the file to the terminal window instead of typing the full path. Hit the Enter key. You'll see the MD5 sum of the file. Match it against the original value.

Which of the following utility creates MD5 hashes for a given file?

In Linux, the md5sum program computes and checks MD5 hash values of a file. It is a constituent of GNU Core Utilities package, therefore comes pre-installed on most, if not all Linux distributions.

What is an MD5 hash of a document?

MD5 Checksum is used to verify the integrity of files, as virtually any change to a file will cause its MD5 hash to change. Most commonly, md5sum is used to verify that a file has not changed as a result of a faulty file transfer, a disk error or non-malicious modification.


2 Answers

Here's the routine I'm currently using.

    using System.Security.Cryptography;      public string HashFile(string filePath)     {         using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))         {             return HashFile(fs);         }     }      public string HashFile( FileStream stream )     {         StringBuilder sb = new StringBuilder();          if( stream != null )         {             stream.Seek( 0, SeekOrigin.Begin );              MD5 md5 = MD5CryptoServiceProvider.Create();             byte[] hash = md5.ComputeHash( stream );             foreach( byte b in hash )                 sb.Append( b.ToString( "x2" ) );              stream.Seek( 0, SeekOrigin.Begin );         }          return sb.ToString();     } 
like image 120
roufamatic Avatar answered Oct 06 '22 04:10

roufamatic


Short and to the point. filename is your text file's name:

using (var md5 = MD5.Create())
{
    return BitConverter.ToString(md5.ComputeHash(File.ReadAllBytes(filename))).Replace("-", "");
}
like image 28
Jesse C. Slicer Avatar answered Oct 06 '22 02:10

Jesse C. Slicer