简体   繁体   中英

MD5 hash for file in C#

How to compute MD5 hash for file in C# in next way:

Compute hash for range 1-4096 bytes -> get MD5 hash for this range;
1-8192 -> get MD5 hash for this range;
1-12288 -> get MD5 hash for this range;
1-16384 -> get MD5 hash for this range;
...
1-end of file -> get MD5 hash for file.

So I always read file using buffer with size 4096 bytes and want to update hash for all read part of file. How to realize it? Looks like MD5CryptoServiceProvider can't help with this task.

Normally, MD5 and other hashes don't work like that. They use a certain padding in the last block. So if you compute the final hash for some bytes, you can't add more bytes to it later. Once you added the final block and computed the hash, it's game over, you have to start again.

I understand you would like to calculate the hash but also keep going further.

The best strategy is to use a custom MD5 implementation that let's you clone its state. When you add one block, duplicate the state of the MD5 algorithm, so you have to MD5 hashers with the same state. You use one of the clones to finish the transformation. You use the other one to go further. Pseudo-code:

hasher = new md5
loop
    read a block of the file
    hasher.addblock(current block)
    hasher2 = hasher.clone()
    hasher.finish()
    hasher = hasher2
end loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM