Adam Jones
Adam Jones

Reputation: 2470

Is it possible to do an md5 check without writing to the filesystem?

Basically I am doing the following:

  1. Download an encrypted file from a web site into a MemoryStream
  2. Decrypt the file
  3. Write the decrypted file out to the file system
  4. Read it back into memory again as a FileStream
  5. Calculate the MD5 and check it.
  6. Send the file to the printer.

Here is my code:

private async void DownloadFileToBePrinted()
{

    using (WebClient client = new WebClient())
    {
        var data = await client.DownloadDataTaskAsync(new Uri(Url));                

        using (var ms = new MemoryStream(data))
        {                    
            valid = DecodeFile(ms);

        }
    }
}

private bool DecodeFile(MemoryStream stream)
{
    bool valid = true;

    try
    {
        using (StreamReader reader = new StreamReader(stream))
        {
            stream.Position = 0;
            var str = reader.ReadToEnd();

            File.WriteAllBytes(FILE_TO_BE_PRINTED, this.Decode(str));

            using (var md5 = MD5.Create())
            {
                using (var fs = File.OpenRead(FILE_TO_BE_PRINTED))
                {
                    var hash = md5.ComputeHash(fs);

                    if (ByteToHex(hash) != FileDetails.MD5) // check against stored md5
                        valid = false;
                }
            }
        }
    }
    catch(Exception ex)
    {
        valid = false;
    }
    return (valid);
}

This seems a bit inefficient, apart from the fact that it is a requirement that a file not be written to the filesystem if it can be avoided.

So I am wondering if it is possible to do this without writing the file out to the file system? If so how?

Upvotes: 1

Views: 652

Answers (1)

AlliterativeAlice
AlliterativeAlice

Reputation: 12577

You can calculate the MD5 without a FileStream like so:

byte[] decoded = this.Decode(str);
var md5 = MD5.Create();
md5.ComputeHash(decoded);

Upvotes: 2

Related Questions