Search code examples
c#monohashcodechecksumsha256

Use a combination of SHA1+MD5, part 2


Previously I asked a question about combining SHA1+MD5 but after that I understand calculating SHA1 and then MD5 of a large file is not that faster than SHA256. In my case a 4.6 GB file takes about 10 mins with the default implementation SHA256 with (C# MONO) in a Linux system.

public static string GetChecksum(string file)
{
    using (FileStream stream = File.OpenRead(file))
    {
        var sha = new SHA256Managed();
        byte[] checksum = sha.ComputeHash(stream);
        return BitConverter.ToString(checksum).Replace("-", String.Empty);
    }
}

Then I read this topic and somehow change my code according what they said to :

public static string GetChecksumBuffered(Stream stream)
{
    using (var bufferedStream = new BufferedStream(stream, 1024 * 32))
    {
        var sha = new SHA256Managed();
        byte[] checksum = sha.ComputeHash(bufferedStream);
        return BitConverter.ToString(checksum).Replace("-", String.Empty);
    }
}

But It doesn't have such a affection and takes about 9 mins.

Then I try to test my file through sha256sum command in Linux for the same file and It takes about 28 secs and both the above code and Linux command give the same result !

Someone advised me to read about differences between Hash Code and Checksum and I reach to this topic that explains the differences.

My Questions are :

  1. What causes such different between the above code and Linux sha256sum in time ?

  2. What does the above code do ? (I mean is it the hash code calculation or checksum calculation? Because if you search about give a hash code of a file and checksum of a file in C#, they both reach to the above code.)

  3. Is there any motivated attack against sha256sum even when SHA256 is collision resistant ?

  4. How can I make my implementation as fast as sha256sum in C#?


Solution

  • public string SHA256CheckSum(string filePath)
    {
        using (SHA256 sha256 = SHA256.Create())
        {
            using (FileStream fileStream = File.OpenRead(filePath))
            {
                return BitConverter.ToString(sha256.ComputeHash(fileStream)).Replace("-", "");
            }
        }
    }