C SQL string filtering method that detects if there are dangerous characters

  • 2020-06-23 01:49:19
  • OfStack

This article takes an C# SQL database string manipulation function as an example to show how to filter SQL strings, detect SQL for dangerous characters, correct escape characters in sql statements, and ensure that SQL is not injected. The specific implementation code is as follows:

SQL string filter function:


public static bool ProcessSqlStr(string Str)
{
  bool ReturnValue = true;
  try
  {
    if (Str.Trim() != "")
    {
      string SqlStr = "exec|insert+|select+|delete|update|count|chr|mid|master+|truncate|char|declare|drop+|drop+table|creat+|create|*|iframe|script|";
      SqlStr += "exec+|insert|delete+|update+|count(|count+|chr+|+mid(|+mid+|+master+|truncate+|char+|+char(|declare+|drop+table|creat+table";
      string[] anySqlStr = SqlStr.Split('|');
      foreach (string ss in anySqlStr)
      {
        if (Str.ToLower().IndexOf(ss) >= 0)
        {
          ReturnValue = false;
          break;
        }
      }
    }
  }
  catch
  {
    ReturnValue = false;
  }
  return ReturnValue;
}

Here are the characters that detect if an SQL statement contains an illegal hazard:


/// <summary>
///  Check if there is Sql Dangerous characters 
/// </summary>
/// <param name="str"> To determine the string </param>
/// <returns> Determine the results </returns>
public static bool IsSafeSqlString(string str)
{
  return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
}
/// <summary>
///  correct sql Escape characters in a statement 
/// </summary>
public static string mashSQL(string str)
{
  string str2;
  if (str == null)
  {
    str2 = "";
  }
  else
  {
    str = str.Replace("\'", "'");
    str2 = str;
  }
  return str2;
}

Related articles: