How to Determine if an Uploaded image is valid

By Peter Bromberg

Hackers often change the content type of their uploads, which could be malicious files. Here is how to guard against this.

       Every image type has an identifying header (the first bytes in the file)

    JPEG: FF D8 in hex
    GIF: The first three bytes are "GIF"
    PNG: 137 80 78 71 13 10 26 10 in decimal

public static bool IsValidImage ( System.IO.Stream stm)  // HttpRequest.InputStream
   {

bool isValid = false;
        char[] header = new char[10];
       StreamReader sr = new StreamReader(stm);
        sr.Read(header, 0, 10);

        // check if JPG
        if (header[0] == 0xFF && header[1] == 0xD8)
        {
            isValid = true;
        }
         // check if GIF
        else if (header[0] == 'G' && header[1] == 'I' && header[2] == 'F')
        {
            isValid = true;
        }
         // check if PNG
        else if (header[0] == 137 && header[1] == 80 && header[2] == 78 && header[3] == 71 && header[4] == 13 && header[5] == 10 && header[6] == 26 && header[7] == 10)
        {
            isValid = true;
        }

return isValid;

    }

How to Determine if an Uploaded image is valid  (1547 Views)