防止sql注入

 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;
        }

    }

posted @ 2018-08-07 11:03  一直乱跑的熊  阅读(192)  评论(0编辑  收藏  举报