Mittwoch, 8. Juni 2011

How to compute the hash code of a file using C#

Hash codes are usefull to find objects in a databas and to check the integrity of a file. This article shows how to compute the RIPEMD-160 checksum of a file using C#

Code sample

The following code sample shows how to compute the checksum of a file using C#. The ComputeHash Method of the RIPEMD160 object creates the hashcode and returns a byte array. The byte array is then transformed to a string of hex numbers.

using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace HashCodeTut
{
    class Program
    {        static void Main(string[] args)
        {
             if 
(args.Length == 0)
                 return;

             string 
hashcode = ComputeHash(args[0]);
             Console.WriteLine(hashcode);
        }
       

        static string  ComputeHash(string filename)
        {
             FileInfo 
fi = new FileInfo(filename);
             FileStream fs = fi.OpenRead();

             RIPEMD160 ripemd = new RIPEMD160Managed();
             byte[] hashbytes = ripemd.ComputeHash(fs);
             fs.Close();
         
             StringBuilder
sb = new StringBuilder();
            
             foreach (byte hb in hashbytes)             
                 sb.AppendFormat(
"{0:X2}", hb);
           

             return sb.ToString();
        }
    }
}

Hash function benchmark

Find a benchmark of the hashing functions RIPEMD160, SHA1, SHA256, SHA384, SHA512 and MD5 here:
Benchmark of hash functions included in Microsoft .Net Framework 4

DiskHash File Compare Tool

The DiskHash File Comper Tool creates hashcodes to detect file system changes.
Download: DiskHash v1.0 File Compare Tool

Keine Kommentare:

Kommentar veröffentlichen