Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with counting MD5 from bitmap stream C#

When im passing Bmp as stream, function always return,

D4-1D-8C-D9-8F-00-B2-04-E9-80-09-98-EC-F8-42-7E

but file saving on disk correctly. When I load bpm from disk, function return correct MD5. Also passing "new Bitmap(int x, int y);" with different value return same MD5.

Why its happening?

    public static string GetMD5Hash()
    {

        Bitmap Bmp = new Bitmap(23, 46); // 
        using (Graphics gfx = Graphics.FromImage(Bmp))
        using (SolidBrush brush = new SolidBrush(Color.FromArgb(32, 44, 2)))
        {
            gfx.FillRectangle(brush, 0, 0, 23, 46);
        }



        using (var md5 = MD5.Create())
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                Bmp.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
 \//EDITED:     Bmp.Save(@"C:\Test\pizdanadysku.bmp"); // Here saving file on disk, im getting diffrent solid color

                return BitConverter.ToString(md5.ComputeHash(memoryStream)); //Always return D4-1D-8C-D9-8F-00-B2-04-E9-80-09-98-EC-F8-42-7E - I noticed that is MD5 of empty 1x1px Bmp file
            } 
        }
    }

Can somebody explain this strange behaviour?

like image 304
Yszty Avatar asked Aug 31 '20 05:08

Yszty


1 Answers

Stream operations tend to only move forward for various reasons (including the fact some streams can only be read, E.g NetworkStream), so saving the image is likely just progressing the stream to the end.

Additionally, and pointed out by various helpful editors (@jpa).

D4-1D-8C-D9-8F-00-B2-04-E9-80-09-98-EC-F8-42-7E

Is the classic MD5 sum of an empty string.

My gut feeling is you just need to reset the position of the stream to get your desired result

memoryStream.Seek(0, SeekOrigin.Begin)
// or 
memoryStream.Position = 0;
like image 185
TheGeneral Avatar answered Nov 08 '22 06:11

TheGeneral