How to calculate the hash of a large fragment of a file?

I want to be able to calculate hashes of arbitrary file sizes in C #.

for example: calculate the 3rd gigabyte hash in a 4gb file.

The main problem is that I do not want to load the entire file into memory, as there may be several files, and offsets can be quite arbitrary.

AFAIK, HashAlgorithm.ComputeHash allows me to use a stream byte buffer. The stream will allow me to efficiently calculate the hash, but for the whole file, not only for a specific fragment.

I was thinking of creating an aan alternative FileStream object and passing it to ComputeHash, where I would overload the FileStream methods and read only for a specific fragment in the file.

Is there a better solution than this, preferably using the C # built-in libraries? Thanks.

+4
source share
5 answers

You must go through either:

  • A byte array containing a piece of data to calculate the hash from
  • A stream that restricts access to the fragment that the computer needs for a hash from

The second option is not so difficult, here is a quick LINQPad program that I dropped together. Please note that it does not have enough error handling, for example, checking that a piece is really available (i.e. that you pass the position and length of the stream that actually exists, and does not fall from the end of the main stream).

, , .

PartialStream :

const long gb = 1024 * 1024 * 1024;
using (var fileStream = new FileStream(@"d:\temp\too_long_file.bin", FileMode.Open))
using (var chunk = new PartialStream(fileStream, 2 * gb, 1 * gb))
{
    var hash = hashAlgorithm.ComputeHash(chunk);
}

LINQPad :

void Main()
{
    var buffer = Enumerable.Range(0, 256).Select(i => (byte)i).ToArray();
    using (var underlying = new MemoryStream(buffer))
    using (var partialStream = new PartialStream(underlying, 64, 32))
    {
        var temp = new byte[1024]; // too much, ensure we don't read past window end
        partialStream.Read(temp, 0, temp.Length);
        temp.Dump();
        // should output 64-95 and then 0 for the rest (64-95 = 32 bytes)
    }
}

public class PartialStream : Stream
{
    private readonly Stream _UnderlyingStream;
    private readonly long _Position;
    private readonly long _Length;

    public PartialStream(Stream underlyingStream, long position, long length)
    {
        if (!underlyingStream.CanRead || !underlyingStream.CanSeek)
            throw new ArgumentException("underlyingStream");

        _UnderlyingStream = underlyingStream;
        _Position = position;
        _Length = length;
        _UnderlyingStream.Position = position;
    }

    public override bool CanRead
    {
        get
        {
            return _UnderlyingStream.CanRead;
        }
    }

    public override bool CanWrite
    {
        get
        {
            return false;
        }
    }

    public override bool CanSeek
    {
        get
        {
            return true;
        }
    }

    public override long Length
    {
        get
        {
            return _Length;
        }
    }

    public override long Position
    {
        get
        {
            return _UnderlyingStream.Position - _Position;
        }

        set
        {
            _UnderlyingStream.Position = value + _Position;
        }
    }

    public override void Flush()
    {
        throw new NotSupportedException();
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        switch (origin)
        {
            case SeekOrigin.Begin:
                return _UnderlyingStream.Seek(_Position + offset, SeekOrigin.Begin) - _Position;

            case SeekOrigin.End:
                return _UnderlyingStream.Seek(_Length + offset, SeekOrigin.Begin) - _Position;

            case SeekOrigin.Current:
                return _UnderlyingStream.Seek(offset, SeekOrigin.Current) - _Position;

            default:
                throw new ArgumentException("origin");
        }
    }

    public override void SetLength(long length)
    {
        throw new NotSupportedException();
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        long left = _Length - Position;
        if (left < count)
            count = (int)left;
        return _UnderlyingStream.Read(buffer, offset, count);
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        throw new NotSupportedException();
    }
}
+4

TransformBlock TransformFinalBlock. , HashAlgorithm.ComputeHash .

- :

using(var hashAlgorithm = new SHA256Managed())
using(var fileStream = new File.OpenRead(...))
{     
    fileStream.Position = ...;
    long bytesToHash = ...;

    var buf = new byte[4 * 1024];
    while(bytesToHash > 0)
    {
        var bytesRead = fileStream.Read(buf, 0, (int)Math.Min(bytesToHash, buf.Length));
        hashAlgorithm.TransformBlock(buf, 0, bytesRead, null, 0);
        bytesToHash -= bytesRead;
        if(bytesRead == 0)
            throw new InvalidOperationException("Unexpected end of stream");
    }
    hashAlgorithm.TransformFinalBlock(buf, 0, 0);
    var hash = hashAlgorithm.Hash;
    return hash;
};
+3

- FileStream - . Stream, Length Position.

? , Stream. :

  • Stream ( , FileStream)

- Streams http://msdn.microsoft.com/en-us/library/system.io.stream%28v=vs.100%29.aspx#inheritanceContinued

+2

, :

LINQPad , :

void Main()
{
    const long gb = 1024 * 1024 * 1024;
    using (var stream = new FileStream(@"d:\temp\largefile.bin", FileMode.Open))
    {
        stream.Position = 2 * gb; // 3rd gb-chunk
        byte[] buffer = new byte[32768];
        long amount = 1 * gb;

        using (var hashAlgorithm = SHA1.Create())
        {
            while (amount > 0)
            {
                int bytesRead = stream.Read(buffer, 0,
                    (int)Math.Min(buffer.Length, amount));

                if (bytesRead > 0)
                {
                    amount -= bytesRead;
                    if (amount > 0)
                        hashAlgorithm.TransformBlock(buffer, 0, bytesRead,
                            buffer, 0);
                    else
                        hashAlgorithm.TransformFinalBlock(buffer, 0, bytesRead);
                }
                else
                    throw new InvalidOperationException();
            }
            hashAlgorithm.Hash.Dump();
        }
    }
}
+1

( " ..." ):

, .

, -, , , . , Stream- , , , .

, - !

0

All Articles