Monday, January 2, 2012

How to calculate file hash piece by piece

Introduction

This C# code shows how to calculate hashes of big files piece by piece, without a need to fully load it to memory first.

Source code

Test project is located here:

https://github.com/vurdalakov/codeblog_examples/tree/master/csharp/bighash

Snippet

    Byte[] CalculateHashPieceByPiece(String fileName)
    {
        const int bufferSize = 65536;
        Byte[] bytes = new byte[bufferSize];

        HashAlgorithm hashAlgorithm = HashAlgorithm.Create("SHA1");

        using (FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
        {
            while (true)
            {
                int bytesRead = stream.Read(bytes, 0, bufferSize);

                if (0 == bytesRead)
                {
                    break;
                }

                hashAlgorithm.TransformBlock(bytes, 0, bytesRead, bytes, 0);
            }

            hashAlgorithm.TransformFinalBlock(bytes, 0, 0);

            return hashAlgorithm.Hash;
        }
    }


See also

  • How to convert a byte array to a hex string
  • No comments:

    Post a Comment