C # BaseStream returns the same MD5 hash no matter what is in the stream

This question says it all. This code

string hash = ""; using (var md5 = System.Security.Cryptography.MD5.Create()) { hash = Convert.ToBase64String(md5.ComputeHash(streamReader.BaseStream)); } 

always returns the same hash.

If I transfer all the data from BaseStream to a MemoryStream, it gives a unique hash every time. The same can be said about the launch.

 string hash = ""; using (var md5 = System.Security.Cryptography.MD5.Create()) { hash = Convert.ToBase64String(md5.ComputeHash( Encoding.ASCII.GetBytes(streamReader.ReadToEnd()))); } 

The second is actually faster, but I heard that this is bad practice.

My question is how to use ComputeHash (stream) correctly. For me, this is always (and I always mean, even if I restart the program, that is, itโ€™s not just hashing the link) returns the same hash, regardless of the data in the stream.

+4
source share
2 answers

The Stream instance is probably located at the end of the stream. ComputeHash returns a hash for bytes from the current position to the end of the stream. Therefore, if the current position is the end of the stream, it will be a hash for null input. Make sure the Stream instance is at the beginning of the stream.

+8
source

I solved this problem by setting stream.Position = 0 before ComputeHash

+2
source

Source: https://habr.com/ru/post/1487152/


All Articles