Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashing multiple byte[]'s together into a single hash with C#?

Tags:

c#

hash

I have three fields: string Title, byte[] Body, and byte[] Data, from which I want to calculate a single hash as a check to be sure they haven't been tampered with or corrupted.

In Python, I can use md5.update() a few times in succession to perform this. But I can't find similar capability in C#. To use MD5.ComputeHash() I'd need to copy all my sources into a single byte[], which is a step I'd like to avoid.

How can I hash it all together into one hash without having to copy the data into a temporary buffer?

like image 610
Scott Stafford Avatar asked Apr 27 '11 13:04

Scott Stafford


2 Answers

There is also solution in .Net Standard and .Net Core using IncrementalHash

IncrementalHash sha256 = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)

// For each block:
sha256.AppendData(block);

// Get the hash code
byte[] hash = sha256.GetHashAndReset();

As pointed out by Eric Lippert, also use SHA256 instead of md5 for better collision resistence.

like image 80
j123b567 Avatar answered Nov 19 '22 16:11

j123b567


Almost all hash algorithms are designed in a way that they can successively be fed with the data in multiple blocks. The result is the same as if the whole data was hashed at once.

Create an instance of e.g. MD5CryptoServiceProvider and call the TransformBlock Method for each block and the TransformFinalBlock Method for the last block:

MD5 md5 = new MD5CryptoServiceProvider();

// For each block:
md5.TransformBlock(block, 0, block.Length, block, 0);

// For last block:
md5.TransformFinalBlock(block, 0, block.Length);

// Get the hash code
byte[] hash = md5.Hash;
like image 20
dtb Avatar answered Nov 19 '22 14:11

dtb