Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

computeHash byte[] and Stream difference

I've been having some trouble with computeHash. I'm using both computeHash(Stream) and computeHash(byte[]). For some reason, they are giving back different result. I've tried writing the byte[] into a MemStream but result was the same when using Byte[]

FileStream zz = new FileStream(t.Filename, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(zz, Encoding.ASCII);
byte[] data = Encoding.ASCII.GetBytes(sr.ReadToEnd());
MemoryStream memStream = new MemoryStream(data);
byte[] test = md5hash.ComputeHash(memStream);

I've closed the file to make sure that the seek position is at the starting point.

zz = new FileStream(t.Filename, FileMode.Open, FileAccess.Read);
zz.Position = 0;
byte[] test1 = md5hash.ComputeHash(zz);

Any suggestions? My only guess is that it's an either an Encoding problem or the Stream has a different size.

Any help would be really appreciated.

Best Regards,
SunSatION

like image 451
SunSatION Avatar asked Nov 06 '22 09:11

SunSatION


1 Answers

Some file encodings have hidden characters to alert a consumer application of the file format. One combination is:



I have a file formatted as UTF8, and ran the following:

byte[] asciidata, streamdata;
using (var zz = new FileStream("utf8.txt", FileMode.Open, FileAccess.Read))
{
    var sr = new StreamReader(zz, Encoding.ASCII);
    asciidata = Encoding.ASCII.GetBytes(sr.ReadToEnd());
}

using (var zz = new FileStream("utf8.txt", FileMode.Open, FileAccess.Read))
{
    streamdata = new byte[asciidata.Length + 3];
    zz.Read(streamdata, 0, streamdata.Length);
}

The variable asciidata contained the four characters in my text file, but streamdata contained the four characters prefixed by the three magic characters described above (for a total of seven characters).

In conclusion, I believe your suspicion that encoding is to blame is correct.

like image 189
kbrimington Avatar answered Nov 13 '22 08:11

kbrimington