Ben
Ben

Reputation: 2465

How to efficiently implement hash validation of a file while using BinaryWriter & Reader?

I'm relatively new to C# so please bear with me.

I am writing a small application in C# (.NET 4.0). For writing files I use some variation of this code:

using (var fStream = new FileStream(filename, FileMode.CreateNew, FileAccess.Write, 
 FileShare.Read))
using (var crypto = new CryptoStream(fStream, encryptor, CryptoStreamMode.Write))
using (var binary = new BinaryWriter(crypto))

I would like to insure that files aren't corrupted and that they don't get tampered. Thus I thought about using sha256 or hmac with sha256 (if it isn't much slower). I don't know how to efficiently implement hashing of file content.

My ideas so far are:

1.) hmac.ComputeHash(stream) - but it doesn't work on binary stream -if I use file stream I don't know which parts of the stream it hashes, because I want to append hash to the end of the file. Thus I don't know when reading how to hash filestream without hashing the appended hash.

2.) use binary stream to read / write to / from memory stream and then call memory.ToArray() and hash that byte array -I think it is quite inefficient

What should I do?

Thank you for your ideas and answers.

Upvotes: 2

Views: 858

Answers (2)

Ben
Ben

Reputation: 2465

I end up using this:

  1. binary stream to read / write in memory
  2. convert memory stream to byte array
  3. hash the byte array

Upvotes: 1

SLaks
SLaks

Reputation: 888213

All HashAlgorithms implement ICryptoTransform.

You can simply read through another CryptoStream around the HashAlgorithm, then check its hash after you finish reading.

Upvotes: 2

Related Questions