Java compressed file detection

Hello to everyone who is kind to read this.

I work with a Java program, I didn’t do it, but I clarified it, the problem is that you can add files, but I want to check that the added files are not compressed in any known person’s format, so I don’t want people to be able to add a zip file or rar or 7z or gz, and so on.

can someone help me with an idea, is this even possible?

early.

* Editing: The program used by IT students adds the files (.java, .class, .php, .doc, .mdb) of their source code, the paths are stored in lines, and at the end the program zips up the files and send them to the teacher, know that the instructor does not want to receive compressed or compressed files, which is the reason for checking.

+1
source share
3 answers

Basically you execute the java equivalent of the unix command typein bytes of a file. Most files have a built-in fingerprint that gives hints to other programs regarding what type of file it has. This imprint is commonly called the "magic number."

7zip - '7', 'z', 0xBC, 0xAF, 0x27, 0x1C
gzip - 0x1F, 0x8B

One (incomplete) list of magic numbers can be found here .

Some files do not have magic numbers, in which case you need to look for other common elements in the file that strongly hint to him a file of a suspicious type.

Based on the file name extension, you simply rename the extension.

+4
source

" " , , ( , ..). . google " ".

+1

FWIW, this function checks if the file is gzipped:

public static boolean isGzipped(File f) {
    InputStream is = null;
    try {
        is = new FileInputStream(f);
        byte [] signature = new byte[2];
        int nread = is.read( signature ); //read the gzip signature
        return nread == 2 && signature[ 0 ] == (byte) 0x1f && signature[ 1 ] == (byte) 0x8b;
    } catch (IOException e) {
        Log.x(e);
        return false;
    } finally {
        Closer.closeSilently(is);
    }
}

See Closer.closeSilently () here.

0
source

Source: https://habr.com/ru/post/1650716/


All Articles