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?
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With