In order to validate an image file I have checked the magic number of the file .Is it possible to change the magic number of the files?

StackOverflow https://stackoverflow.com/questions/22087568

Question

My requirement is to check whether the file is jpeg / jpg / png . I have written the following code.

public boolean isFileValid(File file) throws IOException {
        DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
        int fileSignature = input.readInt();
            input.close();
        logger.info(fileSignature);
        if (fileSignature == 0xffd8ffe0) {
            logger.info("File is jpeg");
            return true;
        } else if(fileSignature == 0x89504E47){
            logger.info("file is in PNG");
            return true;
        } else {return false;}

    }

I am using ubuntu 13.04 and the code above works fine for me.I read that the file signature doesnot vary across various O.S.(i am not very sure of this though as i havenot tested it in other O.S.).Also is it possible to vary the signature of the files? Is there a better way of doing this without using third party libraries?

Was it helpful?

Solution

To begin with, you have wrong JPG magic number. It is not 4 bytes in length, only two and it is 0xffd8 (first half of your magic number). And If I understand what are you asking, then magic numbers are defined by their file type specification and they are supposed to be the same across any platform and at all times. Bluntly speaking, if you have different magic number, it is not the file you are looking for. There are some rare exceptions when the same file type have several magic numbers, but that's usually to be compatible with older/different standarts.

Furthermore, if a file has correct magic number that doesn't necessarily mean that it is file of a correct type. Technically, your approach would "label" file with ONLY magic number as its data as a correct png/jpg image.

Thus, checking magic number is first step (you can think it of as a somewhat "filetype hash value") in process of checking if file is valid png/jpg, but if the magic number check passes, you should continue on analyzing file structure and checking if the file contains meaningful file data according to its specification.

You can easily find the specification (and actual links to official specifications) in wikipedia: http://en.wikipedia.org/wiki/Portable_Network_Graphics#Technical_details http://en.wikipedia.org/wiki/JPEG#Syntax_and_structure

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top