16

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?

3
  • 1
    Why not use the temp variable? Commented Apr 27, 2011 at 13:44
  • 1
    And BTW, I guess python creates a single bytes array under the hood...
    – digEmAll
    Commented Apr 27, 2011 at 13:51
  • 4
    You know that MD5 is broken, right? You say that you are using the hash to detect tampering, but it is computationally feasible for the attacker to tamper with the document without changing the hash. You should be using SHA256 or some other hash algorithm that does not have known collision-resistance problems. Commented Apr 27, 2011 at 14:21

6 Answers 6

25

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.

20

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;
4
  • Seems like a mix of languages? Commented Apr 27, 2011 at 13:54
  • 2
    Can you provide a code example? I see that method but its use eludes me. How do I avoid it overwriting the previous output, for instance? Commented Apr 27, 2011 at 13:57
  • Transform(Final)Block essentially works the same way as update, i.e. it updates the internal state of the MD5 instance with the new data. I've added an example (untested though).
    – dtb
    Commented Apr 27, 2011 at 14:04
  • If lenght of block is not multiple of block size, TransfomFinalBlock() method will destroy context. Answer about IncrementalHash is correct, it will keep context after hash calculation for any data length Commented Mar 26 at 21:14
0

Using plain .NET, I don't think there is a way to update and MD5 hash. However, Windows has an MD5Update function defined in crypt.dll. You could use Interop to leverage this I suppose.

Otherwise, there is an implementation of a PHP equivalent in .NET c#, located here on SO: Problem porting PHP crypt() function to C#

PS: I would definitely go for the combined temp variable solution :-)

0
0

Calling the ComputeHash function on three different values is going to create three different byte array results. Those results will then have to be combined in some way to produce a single hash. There is no way around this fact. It will create three new objects in the heap. It will compute a hash (a fairly slow operation) three times instead of just one.

I think the most performant way to do what you want is to just go ahead and copy your source values into a single byte array and take the hash of that.

You don't say why you want to avoid this approach. I think it wins in terms of simplicity and maintainability. It is the self-documenting, obvious approach. It is the most performant method. I don't really see a down-side.

1
  • The downside is if you had a 1GB file then you'd load that 1GB byte array into memory instead of buffering it for increased performance..
    – Lorenzo
    Commented Mar 23, 2022 at 10:19
-1

you can create a Hash over the Hash values.

MD5 md5 =  System.Security.Cryptography.MD5.Create();
byte[] totalHash= md5.ComputeHash(md5.ComputeHash(part1).Concat(md5t.computeHash(part2)));

doesnt create a copy of the byte array but hashes a concatenation of the hashes.

6
  • +1: Dunno why you got -1'd, it's a reasonable solution IMO (though @dtb's is better :) ). Commented Apr 27, 2011 at 14:23
  • just asked myself why i got the -1. But i agree that dtb's is better :-)
    – fixagon
    Commented Apr 27, 2011 at 14:27
  • 1
    this reduces the crypto strength (on an already weakened MD5), potentially significantly so is to be avoided. (not that I -1'd but I would assume that was the reason). I don't believe it's anywhere near so horrid as Guffa's suggestion but it's not a good idea to roll your own crypto in this way (even if the building blocks are good)
    – ShuggyCoUk
    Commented Apr 27, 2011 at 14:42
  • how exactly is it reducing the crypto strength? (i dont deny that it does, just wondering). if we assume that MD5 would be safe (no collisions reconstructable) it doesnt really matter how often i run the algorithm over its own produced hash, it wont get more secure, but neither less?
    – fixagon
    Commented Apr 27, 2011 at 14:55
  • 2
    because someone no longer needs to find a collision in XYZ, they need to find a collision in either X, Y, Z or X'Y'Z (where V' is hash(V)).
    – ShuggyCoUk
    Commented Apr 27, 2011 at 16:01
-1

You have to combine them all in a single variable and then calculate the MD5 Hash. I don't see any shortcut there.

You see, most of solutions proposed here just try either to run multiple commands on the same line ("one liners") or implement something to "under the hood" combine your fields and then Hash...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.