62,046
社区成员
发帖
与我相关
我的任务
分享
public class badWordsFilter
{
private int maxLength = 0;
private ulong[] charBits;
private ulong[] charWords;
private HashSet<string> words;
public badWordsFilter(string[] badwords)
{
if (badwords != null && badwords.Length != 0)
{
foreach (string badword in badwords)
{
if (badword != null && badword.Length != 0)
{
if (maxLength == 0)
{
charBits = new ulong[4096];
charWords = new ulong[4096];
words = new HashSet<string>();
}
if ((badword.Length == 1 ? (!charWords.getBit(badword[0])) : (!words.Contains(badword))))
{
if (badword.Length == 1)
{
if (maxLength == 0) maxLength = 1;
charWords.setBit(badword[0], true);
charBits.setBit(badword[0], true);
}
else
{
if (badword.Length > maxLength) maxLength = badword.Length;
words.Add(badword);
foreach (char badChar in badword) charBits.setBit(badChar, true);
}
}
}
}
}
}
public bool hasBadWord(string content)
{
bool noBadWord = true;
if (content != null && content.Length != 0 && maxLength != 0)
{
int endLength, length, startIndex = 0, index = 0;
foreach (char c in content)
{
if (charBits.getBit(c))
{
if (charWords.getBit(c)) noBadWord = false;
index++;
}
else
{
if (maxLength != 1)
{
while (noBadWord && startIndex < index - 1)
{
for (length = 2, endLength = Math.Min(maxLength, index - startIndex); noBadWord && length <= endLength; length++)
{
noBadWord = !words.Contains(content.Substring(startIndex, length));
}
startIndex++;
}
}
startIndex = ++index;
}
if (!noBadWord) break;
}
if (noBadWord && maxLength != 1)
{
while (noBadWord && startIndex < index - 1)
{
for (length = 2, endLength = Math.Min(maxLength, index - startIndex); noBadWord && length <= endLength; length++)
{
noBadWord = !words.Contains(content.Substring(startIndex, length));
}
startIndex++;
}
}
}
return !noBadWord;
}
}
public static void setBit(this ulong[] bits, long bitIndex, bool isBit)
{
if (bits != null && bits.Length != 0 && bitIndex >= 0)
{
int index = (int)(bitIndex >> 6);
if (index < bits.Length)
{
ulong andValue = (1UL << (int)(bitIndex & 63));
bits[index] |= andValue;
if (!isBit) bits[index] -= andValue;
}
}
}
public static bool getBit(this ulong[] bits, long bitIndex)
{
bool isBit = false;
if (bits != null && bits.Length != 0 && bitIndex >= 0)
{
int index = (int)(bitIndex >> 6);
isBit = (index < bits.Length) && (bits[index] & (1UL << (int)(bitIndex & 63))) != 0;
}
return isBit;
}
void Application_BeginRequest(object sender, EventArgs e)
{
if (Regex.IsMatch(Request.RawUrl.ToLower(), @"/manager/")==false)//不检查manager目录
for (int i=0; i < Request.Form.Count;i++)//遍历Post参数,隐藏域除外
{
if (Request.Form[i].ToString() == "__VIEWSTATE") continue;
if (IsDanger(Request.Form[i].ToString()))
{
Response.Write("您提交的内容中含有非法字符,已经被拒绝.");
Response.End();
}
}
}
protected bool IsDanger(string InText)
{
string word = @"exec|insert|select|delete|update|master|truncate|char|declare|join|
iframe|href|script|<|>|request";
if (InText == null)
return false;
if (Regex.IsMatch(InText,word))
return true;
return false;
}