"Turn" How to use Java to format and inspect images and to handle security checks

Source: Internet
Author: User

This article is from Feng Libin's blog, the original address: http://www.fenglibin.com/use_java_to_check_images_type_and_security.html

One, usually, to verify whether a file is a picture, can be done in the following three ways:

1), determine if the file extension is the required picture extension

This kind of judgment is used more than a way, but this way is very inappropriate, others slightly to the image of a file extension is modified to the extension of the picture, bypassing your this check, if this upload file is shell, PHP or JSP, Then your website can basically be said to be in the hands of others.

However, this way of judging is not completely useless, we can put it in judging the outermost layer of the image, if a file extension is not the name of the image extension we require, it does not have the following content format check, to a certain extent, to reduce the pressure on the server is still a certain help, Otherwise, all the files are uploaded and then after the server to judge, that will be to a certain extent waste the resources of the device.

2), according to the file in front of a few bytes, that is often said magic number to judge, different file types of the beginning of a few bytes, you can view my other station introduction: Magic numbers representing different file types.

But this way of judging is also very unreliable, because he can only verify the first few bytes of the file, so when someone has an executable php file extension modified to PNG, and then in front of the "89 50″ two bytes, and then bypass the authentication method."

Here is a sample program that gets the first two bytes of a file through Java code:

1 ImportJava.io.File;2 ImportJava.io.FileInputStream;3 Importjava.io.IOException;4 ImportJava.io.InputStream;5  6  Public classImagetypecheck {7  8      Public StaticString bytestohexstring (byte[] src) {9StringBuilder StringBuilder =NewStringBuilder ();Ten         if(src = =NULL|| Src.length <= 0) { One             return NULL; A         } -          for(inti = 0; i < src.length; i++) { -             intv = src[i] & 0xFF; theString HV =integer.tohexstring (v); -             if(Hv.length () < 2) { -Stringbuilder.append (0); -             } + stringbuilder.append (HV); -         } +         returnstringbuilder.tostring (); A     } at      Public Static voidMain (string[] args)throwsIOException { -String ImagePath = "C:/favicon.png"; -File image =NewFile (imagePath); -InputStream is =NewFileInputStream (image); -         byte[] bt =New byte[2]; - Is.read (BT); in System.out.println (bytestohexstring (BT)); -     } to}

However, this way of judging and judging the extension of the same, is not completely useless, at least in the early stage in a simple check, for the next check to do the groundwork.

3), get the width and height properties of the picture
If you can normally get to a picture of the width of the high property, that is sure this is a picture, because non-image file We are not able to get its wide-height property, the following is used to get a picture based on whether you can get the width of the high property to determine whether this is a picture of the Java code:

1     /**2 * It is a very simple way to judge whether the current file is a picture by reading the file and getting its width and height. 3      * 4      * @paramImageFile5      * @return6      */7      Public Static Booleanisimage (File imagefile) {8         if(!imagefile.exists ()) {9             return false;Ten         } OneImage img =NULL; A         Try { -IMG =Imageio.read (imagefile); -             if(img = =NULL|| Img.getwidth (NULL) <= 0 | | Img.getheight (NULL) <= 0) { the                 return false; -             } -             return true; -}Catch(Exception e) { +             return false; -}finally { +IMG =NULL; A         } at}

Second, the picture file Security check processing
Well, we finally determine whether a file is a picture, but if it is in a normal view of the image file to add some illegal code:

This is in a normal image at the end of the addition of some of the IFRAME code, I have tried to open this image alone, but also put this picture on the Web page open, although this will not be executed, but does not mean that the insertion of other code will not be executed, anti-virus software (such as Avast) is reported as a virus.
So how do we prevent this, that can be opened normally, with the correct image file extension, but also to get its wide-height properties? Oh, we can at this time to rewrite the image, to add a watermark or to resize it, so that the newly generated image will not contain such malicious code, the following is a watermark added Java implementation:

1 /**2 * Add image Watermark3      * 4      * @paramsrcimg target picture path, such as: C:\\kutuku.jpg5      * @paramwaterimg watermark Picture path, such as: C:\\kutuku.png6      * @paramThe x-watermark image is offset from the left side of the target image, if x<0, in the middle7      * @paramy watermark image offset from the upper side of the target image, if y<0, in the middle8      * @paramAlpha Transparency (0.0--1.0, 0.0 full transparent, 1.0 completely opaque)9      * @throwsIOExceptionTen      */ One      Public Final Static voidAddwatermark (String srcimg, String waterimg,intXintYfloatAlphathrowsIOException { A         //loading the target picture -File File =NewFile (srcimg); -String ext = srcimg.substring (Srcimg.lastindexof (".") + 1); theImage image =imageio.read (file); -         intwidth = image.getwidth (NULL); -         intHeight = image.getheight (NULL); -   +         //loads the target picture into memory.  -BufferedImage BufferedImage =Newbufferedimage (width, height, bufferedimage.type_int_rgb); +Graphics2D g =bufferedimage.creategraphics (); AG.drawimage (image, 0, 0, width, height,NULL); at   -         //loads the watermark picture.  -Image waterimage = Imageio.read (NewFile (waterimg)); -         intwidth_1 = Waterimage.getwidth (NULL); -         intHeight_1 = Waterimage.getheight (NULL); -         //sets the transparency of the watermark picture.  in G.setcomposite (alphacomposite.getinstance (alphacomposite.src_atop, Alpha)); -   to         //sets the location of the watermark picture.  +         intWidthdiff = width-width_1; -         intHeightdiff = height-height_1; the         if(X < 0) { *x = WIDTHDIFF/2; $}Else if(X >Widthdiff) {Panax Notoginsengx =Widthdiff; -         } the         if(Y < 0) { +y = Heightdiff/2; A}Else if(Y >Heightdiff) { they =Heightdiff; +         } -   $         //The watermark picture is "painted" in the original position of the picture.  $G.drawimage (Waterimage, x, Y, width_1, height_1,NULL); -         //close the brush.  - g.dispose (); the   -         //Save the target picture. Wuyi Imageio.write (bufferedimage, ext, file); the}

Through the above ways, it should be possible to avoid the majority of images with malicious code security issues, but because of my personal caishuxueqian, there may be no thoughtful place, but also ask you to feel free.

"Turn" How to use Java to format and inspect images and to handle security checks

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.