实用技巧——检测字符串在SQL中是否危险

      /// <summary>
        /// 检测字符串中是否有SQL攻击代码
        /// </summary>
        /// <param name="sqlString">待检测的字符串</param>
        /// <returns>True:不危险,False:危险</returns>
        public static bool IsSecurity(string sqlString)
        {
            if (string.IsNullOrWhiteSpace(sqlString))
                return false;
            string SqlStr = @"and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|\*|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators";
            string str_Regex = @"\b(" + SqlStr + @")\b";

            Regex regex = new Regex(str_Regex, RegexOptions.IgnoreCase);
            if (regex.IsMatch(sqlString))
                return false;
            return true;
        }

        /// <summary>
        /// 过滤危险SQL字符
        /// </summary>
        public static string FilterString(string sqlString)
        {
            string SqlStr = @"and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|\*|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators";
            if (string.IsNullOrWhiteSpace(sqlString))
                return sqlString;

            string str_Regex = @"\b(" + SqlStr + @")\b";

            //替换危险字符串
            sqlString = Regex.Replace(sqlString, str_Regex, "", RegexOptions.IgnoreCase);
            return sqlString;
        }
    }
posted @ 2010-07-06 13:21  曼阳  阅读(672)  评论(1编辑  收藏  举报