首页 > 数据库技术 > 详细

防止sql注入

时间:2018-08-07 12:00:33      阅读:186      评论:0      收藏:0      [点我收藏+]

 public static class SQLDefenderHelper
    {
      

        public static string SQLFilter(string inText)
        {
            string word = "and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join|--|on|=|‘|+";
            if (inText == null)
                return inText;
            //防止\**\代替空格
            if (inText.Contains("\\") || inText.Contains("/"))
            {
                InitInfo.LogOperation._OperationInfoLog("", "SQLDefenderHelper.SqlFilter", string.Format("语句{0}存在风险,禁止执行!", inText), "");
                throw new Exception("SQL语句存在风险,禁止执行!");
            }
            if (inText.Count(a => a.Equals(‘\‘‘)) % 2 != 0)//单引号为奇数则认为有风险
            {
                InitInfo.LogOperation._OperationInfoLog("", "SQLDefenderHelper.SqlFilter", string.Format("语句{0}存在风险,禁止执行!", inText), "");
                throw new Exception("SQL语句存在风险,禁止执行!");
            }

            foreach (string i in word.Split(‘|‘))
            {
                if ((inText.ToLower().IndexOf(i + " ") > -1) || (inText.ToLower().IndexOf(" " + i) > -1) ||//防止空格
                  (i!= "‘"&&inText.ToLower().IndexOf(i + "(") > -1) || (i != "‘" & inText.ToLower().IndexOf(")" + i) > -1) || //防止括号代替空格
                  (inText.ToLower().IndexOf(i + "\n") > -1) || (inText.ToLower().IndexOf("\n" + i) > -1) ||  //防止回车代替空格
                  (inText.ToLower().IndexOf(i + "\t") > -1) || (inText.ToLower().IndexOf("\t" + i) > -1))   //防止TAB代替空格
                {
                    InitInfo.LogOperation._OperationInfoLog("", "SQLDefenderHelper.SqlFilter", string.Format("语句{0}存在风险,禁止执行!", inText), "");
                    throw new System.Exception("SQL语句存在风险,禁止执行!");
                }
            }

            Regex regex = new Regex(@"[^0-9a-zA-Z,‘\(\)\*\.\-]+");
            if (regex.IsMatch(inText))
            {
                InitInfo.LogOperation._OperationInfoLog("", "SQLDefenderHelper.SqlFilter", string.Format("语句{0}存在风险,禁止执行!", inText), "");
                throw new System.Exception("SQL语句存在风险,禁止执行!");
            }
            return inText;
        }

    }

防止sql注入

原文:https://www.cnblogs.com/ZX-LMY/p/9435783.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!