Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# BaseStream returning same MD5 hash regardless of what is in the stream

The question says it all. This code

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

will always return the same hash.

If I pass all of the data from the BaseStream into a MemoryStream, it gives a unique hash every time. The same goes for running

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

The second one is actually faster, but I've heard it's bad practice.

My question is, what is the proper way to use ComputeHash(stream). For me it always (and I mean always, even if I restart the program, meaning it's not just hashing the reference) returns the same hash, regardless of the data in the stream.

like image 467
JBarber Avatar asked Jun 19 '13 21:06

JBarber


2 Answers

The Stream instance is likely positioned at the end of the stream. ComputeHash returns the hash for the bytes from the current position to the end of the stream. So if the current position is the end of the stream, it will the hash for the empty input. Make sure that the Stream instance is positioned at the beginning of the stream.

like image 149
dtb Avatar answered Nov 17 '22 17:11

dtb


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

like image 33
San Kira Avatar answered Nov 17 '22 15:11

San Kira