Asp. NET upload file format through byte correct security judgment-practical tips

Source: Internet
Author: User
Tags sqlite database

Asp. NET in the decision file format, we used to use the method is to intercept the extension to make judgments, or by ContentType (MIME), both methods are not very safe, because the two ways users can forge, so that can attack the site, to achieve the purpose of hanging the site.

Here's how to make a judgment by getting file types in byte

if (Request.Files.Count > 0)
{
  ///Here only Test upload first picture file[0]
  httppostedfile FILE0 = request.files[0];
    
  Convert to Byte, read picture MIME type
  stream stream;
  int contentlength = File0. ContentLength; File length
  byte[] filebyte = new Byte[2];//contentlength, here we read only the first two bits of the file length used for judgment, so the speed is faster and the rest is not available.
  stream = File0. InputStream;
  Stream. Read (filebyte, 0, 2),//contentlength, or take the first two-bit
  stream. Close ();
    
  String fileflag = "";
  if (filebyte!= null && filebyte.length > 0)//Picture data is empty
  {
    Fileflag = filebyte[0]. ToString () + filebyte[1]. ToString ();         
  }
  String[] Filetypestr = {"255216", "7173", "6677", "13780"};//corresponding picture format jpg,gif,bmp,png
  if (Filetypestr.contains ( Fileflag))
  {
    file0. SaveAs (Server.MapPath) ("~/" + FILE0. FileName));
  }
  else
  {
    Response.Write (incorrect picture format: + Fileflag);
  }
}

Byte data for common file types

199196 SQLite database files
7076 FLV video Files
6787 SWF video files
7173 Gif
255216 Jpg
13780 Png
6677 Bmp
239187 Txt,aspx,asp,sql
208207 Xls.doc.ppt
6063 Xml
6033 Htm,html
4742 Js
8075 Xlsx,zip,pptx,mmap,zip,docx
8297 rar
01 Accdb,mdb
7790 Exe,dll
5666 Psd
255254 Rdp
10056 BT seeds
64101 Bat
255254 Csv
3780 Pdf
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.