这些天,csdn上讨论sql注入攻击似乎是如火如荼啊...我也来参合一下..
如下,checkparams函数,接收参数任意,如参数中有字符串,则对字符串进行检查,如参数中有集合(如array之类,总之是实现了icollection的),则对集合中的字符串元素进行检查.
大家可根据具体情况来定要过滤的字符,我这个例子里暂定为=号和'号,实际上我个人认为,过滤了这两个,似乎要进行sql注入就已经比较困难了,当然,我对sql是菜鸟,欢迎高手指正,谢谢.我的邮箱(msn): [email protected]
bool checkparams(params object[] args)
{
 string[] lawlesses={"=","'"};
 if(lawlesses==null||lawlesses.length<=0)return true;
 //构造正则表达式,例:lawlesses是=号和'号,则正则表达式为 .*[=}'].* (正则表达式相关内容请见msdn)
 //另外,由于我是想做通用而且容易修改的函数,所以多了一步由字符数组到正则表达式,实际使用中,直接写正则表达式亦可;
 string str_regex=".*[";
 for(int i=0;i< lawlesses.length-1;i++)
 str_regex+=lawlesses[i]+"|";
 str_regex+=lawlesses[lawlesses.length-1]+"].*";
 //
 foreach(object arg in args)
 {
 if(arg is string)//如果是字符串,直接检查
 {
 if(regex.matches(arg.tostring(),str_regex).count>0)
 return false;
 }
 else if(arg is icollection)//如果是一个集合,则检查集合内元素是否字符串,是字符串,就进行检查
 {
 foreach(object obj in (icollection)arg)
 {
 if(obj is string)
 {
 if(regex.matches(obj.tostring(),str_regex).count>0)
 return false;
 }
 }
 }
 }
 return true;
}