Java to determine the type of uploaded files through the magic number __java

Source: Internet
Author: User

Preface

File Upload function is a lot of Web sites must function, and the decision file type can not only filter file upload, but also to prevent users upload malicious executable files and scripts, as well as the file upload server as a free file storage server use.

For uploading files, it is not easy to determine the type of file by suffix name, because a malicious attack can change the name of the executable file suffix to a picture or other format, inducing the user to execute, therefore, to determine the type of upload file needs a more secure way.

Similar to the Java class file, many types of files, starting with a few bytes of content are fixed, according to the contents of these bytes, you can determine the type of file, these several bytes are also known as "magic number", such as the number of the Magic class file is "Cafebabe."

It is a more secure way to judge a file type by magic number, and its example source code is as follows.

Source Code

1. Create a new enumeration class for a file type

public enum FileType {/** JPEG */jpeg ("FFD8FF"),/** PNG/png ("89504E47"),/** gif/gif ( "47494638"),/** TIFF */TIFF ("49492a00"),/** Windows bitmap/BMP ("424D"),/** CAD/DWG ("4 1433130 "),/** Adobe Photoshop/PSD (" 38425053 "),/** rich Text Format */RTF (" 7b5c727466 "),/** X ML/XML ("3c3f786d6c"),/** HTML/html ("68746d6c3e"),/** Outlook Express */DBX ("cfad12fec5fd746 F "),/** Outlook */PST (" 2142444E "),/** doc;xls;dot;ppt;xla;ppa;pps;pot;msi;sdw;db/OLE2 (" 0xd0cf11e0 A1b11ae1 "),/** Microsoft Word/excel/Xls_doc (" D0cf11e0 "),/** Microsoft Access */MDB (" 5374616E646172 64204A "),/** Word Perfect * * WPB (" FF575043 "),/** Postscript/Eps_ps (" 252150532d41646f6265 "),/*
    * Adobe Acrobat/PDF ("255044462d312e"),/** Windows Password/PWL ("E3828596"),/** ZIP Archive * *

    ZIP ("504b0304"),/** ARAR Archive/RAR ("52617221"),/** WAVE/WAV ("57415645"),/** avi/avi ("41564920"),/ * * Real Audio/RAM ("2E7261FD"),/** Real Media */RM ("2e524d46"),/** Quicktime/MOV ("6d6f6f76")

    ,/** Windows Media/ASF ("3026b2758e66cf11"),/** MIDI */MID ("4d546864");

    Private String value = "";
    Private FileType (String value) {this.value = value;
    Public String GetValue () {return value;
    public void SetValue (String value) {this.value = value;
 }

}

2. Create a new File tool class to determine the type of uploaded file

Import Java.io.FileInputStream;
Import java.io.IOException;


Import Java.io.InputStream;
        public class Filutil {/** judge file type * * public static FileType GetType (String filePath) throws IOException {

        Gets the file header String Filehead = GetFileHeader (FilePath);
            if (filehead!= null && filehead.length () > 0) {filehead = Filehead.touppercase ();

            filetype[] FileTypes = Filetype.values (); for (FileType type:filetypes) {if (Filehead.startswith (Type.getvalue ())) {return T
                ype;
    }} return null; /** read file header/private static string GetFileHeader (String filePath) throws IOException {byte[] b = new B
        YTE[28];

        InputStream inputstream = null;
            try {inputstream = new FileInputStream (FilePath);
        Inputstream.read (b, 0, 28);
      finally {if (InputStream!= null) {          Inputstream.close ();
    } return Bytestohex (b);  /** converts a byte array to a 16-character string */public static string Bytestohex (byte[] src) {StringBuilder StringBuilder = new  
        StringBuilder ("");  
        if (src = null | | | src.length <= 0) {return null;  
            for (int i = 0; i < src.length i++) {int v = src[i] & 0xFF;  
            String HV = integer.tohexstring (v);  
            if (Hv.length () < 2) {stringbuilder.append (0);  
        } stringbuilder.append (HV);  
    return stringbuilder.tostring ();
 } 

}

Above, it should be noted that there may be one type of file with the same magic number as the previous part of the other type file magic number (such as ' d0cf11e0 ' and ' d0cf11e0a1b11ae1 '), so you should try to put a longer magic value on it. The files and magic numbers are not fully enumerated here, but that's the way it is.

Reference Documents
[1] Chen Kang. Design and practice of large distributed Web site architecture [M]. Beijing: Electronic industry publishing house. 2014.09

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.