Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I compute files hash(md5 & SHA1) in C#

This is my first C# project and I'm almost newbie. I use openfiledialoge for selecting file and get the filepath by GetFullPath method and store it in a variable called for example fpath. I need to calculate the hash of the file that its path is stored in fpath variable.I think it can be done via GetHashCode. Can anybody give me a snippet or a little guide?

like image 719
n1kita Avatar asked Nov 26 '12 16:11

n1kita


People also ask

Is MD5 good enough for checksum?

A checksum algorithm in this scenario only needs to be 'good enough' to detect unintentional changes to the data. For example, MD5 is perfectly suitable - it is a very widely adopted, there is good tool support, and checksums are quick to generate and compare.

How long does it take to compute MD5?

It generally takes 3-4 hours to transfer via NC and then 40 minutes to get the md5sum. The security of the hash is not an issue in this case.

How are file checksums calculated?

The checksum is calculated using a hash function and is normally posted along with the download. To verify the integrity of the file, a user calculates the checksum using a checksum calculator program and then compares the two to make sure they match.


2 Answers

using (FileStream stream = File.OpenRead(file))
{
    SHA256Managed sha = new SHA256Managed();
    byte[] hash = sha.ComputeHash(stream);
    return BitConverter.ToString(hash).Replace("-", String.Empty);
}
like image 179
Saddam Abu Ghaida Avatar answered Oct 13 '22 01:10

Saddam Abu Ghaida


Here is a complete code using C# managed library to compute the hash.

using system.IO;
using System.Security.Cryptography;

public string GetSha1Hash(string filePath)
{
    using (FileStream fs = File.OpenRead(filePath))
    {
        SHA1 sha = new SHA1Managed();
        return BitConverter.ToString(sha.ComputeHash(fs));
    }
}
like image 20
Tony Avatar answered Oct 13 '22 01:10

Tony