上传图片的综合验证


        #region 私有变量
        private static string path = "";
        //"script",
        private static List<string> chkList = new List<string>();
        //private static string[] chkList = {"include","filesystemobject","shell.application","request",".getfolder",".createfolder",".deletefolder",".createdirectory",".deletedirectory",".saveas","wscript.shell","script.encode","server.",".createobject","execute","activexobject","language=","<%","&lt;%","session"};
        #endregion


        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(path))
            {
                path = Page.Server.MapPath("~\\Pictrue\\");
            }
            if (chkList.Count < 1)
            {
                string chkStr = ConfigurationManager.AppSettings["CodeCheck"];
                string[] chks = chkStr.Split(',');
                foreach (string str in chks)
                {
                    chkList.Add(str);
                }
                chkList.Add("<%");
                chkList.Add("&lt;%");
            }
            string result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Data>\r\n";
            result = SaveFile(result);
            result += "</Data>";
            Response.ContentType = "text/xml";
            Response.ContentEncoding = Encoding.UTF8;
            Response.Write(result);
            Response.End();
        }


        public string SaveFile(string result)
        {
            try
            {
                string key = ConfigurationManager.AppSettings["AppKey"];
                string type = Request["type"];
                string id = Request["id"];
                string sign = Request["sign"];
                string timestamp = Request["timestamp"];
                if (   string.IsNullOrEmpty(type)
                    || string.IsNullOrEmpty(id)
                    || string.IsNullOrEmpty(sign)
                    || string.IsNullOrEmpty(timestamp))
                {
                    result += "<Code>1001</Code>\r\n";
                    result += "<Message>缺少参数</Message>\r\n";
                    return result;
                }
                int minute = int.Parse(timestamp.Substring(10,2));
                int second = int.Parse(timestamp.Substring(12,2));
                if ((minute * 60 + second + 60) < (DateTime.Now.Minute * 60 + DateTime.Now.Second))
                {
                    result += "<Code>1007</Code>\r\n";
                    result += "<Message>时间已过期</Message>\r\n";
                    return result;
                }
                string newSign = Tools.EncryptMd5UTF8("id=" + id + "&timestamp=" + timestamp + "&type=ts" + key);
                if(sign.ToLower() != newSign)
                {
                    result += "<Code>1002</Code>\r\n";
                    result += "<Message>参数验证错误</Message>\r\n";
                    return result;
                }
                string imgPath = path + type.ToUpper() + "\\" + id.ToUpper() + "\\" + timestamp.ToUpper();
                if (!Directory.Exists(imgPath))
                {
                    Directory.CreateDirectory(imgPath);
                }
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    HttpPostedFile filePost = Request.Files[i];
                    string ImgName = filePost.FileName.Substring(filePost.FileName.LastIndexOf('\\') + 1);


                    #region 基本验证
                    int ImgSize = filePost.ContentLength;
                    if (ImgSize == 0 || string.IsNullOrEmpty(ImgName))
                    {
                        continue;
                    }
                    string savePath = imgPath + "\\" + ImgName;
                    #endregion


                    #region 验证图片大小
                    if (ImgSize > 2048 * 1024)
                    {//大于2M
                        result += "<Code>1003</Code>\r\n";
                        result += "<Message>图片【" + ImgName + "】大小超过2M</Message>\r\n";
                        return result;
                    }
                    #endregion


                    #region 验证图片是否附加恶意代码
                    byte[] buff = new byte[ImgSize];
                    filePost.InputStream.Read(buff, 0, ImgSize);
                    filePost.InputStream.Seek(0, SeekOrigin.Begin); 
                    string imgStr = Encoding.Default.GetString(buff);
                    string strContent = imgStr.ToLower();
                    foreach (string s in chkList)
                    {
                        if (strContent.IndexOf(s) != -1)
                        {
                            result += "<Code>1004</Code>\r\n";
                            result += "<Message>图片【" + ImgName + "】包含恶意代码</Message>\r\n";
                            Tools.Log("图片【" + ImgName + "】包含恶意代码【" + s + "】原串为【" + strContent + "】");
                            return result;
                        }
                    }
                    #endregion


                    #region 验证图片类型
                    //验证文件后缀名
                    string ImgType = Path.GetExtension(filePost.FileName);
                    if (ImgType.ToLower() != ".bmp" && ImgType.ToLower() != ".jpg" && ImgType.ToLower() != ".jpeg")
                    {
                        result += "<Code>1005</Code>\r\n";
                        result += "<Message>图片【" + ImgName + "】格式不正确, 请选择.bmp/.jpg/.jpeg类型的图片</Message>\r\n";
                        return result;
                    }


                    //验证文件内容格式
                    //8297:RAR|255216:jpg|7173:gif||6677:bmp|13780:png|7790:exe dll|8297:rar|6063:xml|6033:html|239187:aspx|117115:cs|119105:js|210187:txt|255254:sql    
                    //1.Png图片文件包括8字节:89 50 4E 47 0D 0A 1A 0A。即为 .PNG....。 
                    //2.Jpg图片文件包括2字节:FF D8。
                    //3.Gif图片文件包括6字节:47 49 46 38 39|37 61 。即为 GIF89(7)a。
                    //4.Bmp图片文件包括2字节:42 4D。即为 BM。
                    byte[] head = new byte[2];//这里只判断j是否为jpg格式 所以获取前两个字节就可以 
                    filePost.InputStream.Read(head, 0, head.Length);
                    filePost.InputStream.Seek(0, SeekOrigin.Begin);
                    if ((head[0] == 255 && head[1] == 216)
                        || (head[0] == 66 && head[1] == 77))
                    {//jpg or bmp
                        filePost.SaveAs(savePath);
                    }
                    else 
                    {
                        result += "<Code>1005</Code>\r\n";
                        result += "<Message>图片【" + ImgName + "】格式不正确, 请选择.bmp/.jpg/.jpeg类型的图片</Message>\r\n";
                        return result;
                    }
                    #endregion
                }
                result += "<Code>1000</Code>\r\n";
                result += "<Message>图片保存成功</Message>\r\n";
                return result;
            }
            catch (Exception ex)
            {
                Tools.Log("SaveFile error:" + ex.Message);
                result += "<Code>1006</Code>\r\n";
                result += "<Message>内部错误,请稍后重试</Message>\r\n";
                return result;
            }
        }
原文地址:https://www.cnblogs.com/foren/p/6009111.html