1

I'm trying to compute an MD5 hash using an HttpPostedFile's InputStream.

There aren't any issues creating the hash or converting the hash. However, the hash is the same, no matter what file I upload (using ASP FileUpload control).

I saw a solution involving setting the Stream.Position = 0 before ComputeHash, but it is still the same.

Is HttpPostedFile.InputStream always going to create the same MD5 hash or is there something I am missing in my code?

I'd appreciate any suggestions. Thanks in advance.

private static string GetMd5FileHash(HttpPostedFile file)
    {
        using (var md5 = MD5.Create())
        {
            file.InputStream.Position = 0;
            var hash = md5.ComputeHash(file.InputStream);
            return Convert.ToBase64String(hash);
        }
    }

UPDATE:

Just discovered that the MD5 hash I've been receiving is generic, which probably means it's not reading the InputStream.

terbubbs
  • 1,512
  • 2
  • 25
  • 48
  • 2
    Have you checked whether `InputStream` contains different length for each call and have different bytes in it? – Sriram Sakthivel Oct 30 '15 at 13:32
  • @SriramSakthivel that's a good point. The files are identical in size even though they do not contain identical data... – terbubbs Oct 30 '15 at 13:33
  • 1
    I tested your method and it work properly. – Mariusz Oct 30 '15 at 13:54
  • 1
    Try doing the same thing but using a different hash method. If Sha256 is also identical, then you are reading in the same bytes twice. Heres a tip, google the hash, if its empty or full of zeroes or some other common pattern, its very likely to appear in a google search. – WHol Oct 30 '15 at 13:56
  • @WHol I believe that is what is happening, but how can two separate files containing different data (although it's the same size) have the same bytes? – terbubbs Oct 30 '15 at 13:58
  • 1
    They wont, but you should rule out the chance you are actually reading the same data. – WHol Oct 30 '15 at 14:01
  • @WHol well it definitely isn't the same data. I've got two CSV excel files that I'm uploading but they aren't identical. They may have identical amount of rows and columns tho, so I wonder if that is an issue. – terbubbs Oct 30 '15 at 14:05
  • 1
    Yes but it seems clear to me that the data is not in that stream. Write the stream to a file and you will probably see that its empty, or contains some kind of error code. https://stackoverflow.com/questions/411592/how-do-i-save-a-stream-to-a-file-in-c Alternatively, read it to a buffer and step through the buffer in a breakpoint. – WHol Oct 30 '15 at 14:06
  • @WHol I just realized something.. The first thing I do with the file is read into the FileHelpers dll that converts it to a model in my code. If the InputStream is read once, does resetting the position help it or can it never be read again? – terbubbs Oct 30 '15 at 14:08

0 Answers0