Advertisement
hubert17

Sanitize input strings against SQL injection using Regex

Oct 2nd, 2014
737
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.45 KB | None | 0 0
  1. /*
  2.     Sanitize input strings against SQL injection using Regex
  3.     If SqlParameters cannot be used this is an anti-pattern that will do the job ( C# ):
  4.  */
  5.  
  6. using System;
  7. using System.Text.RegularExpressions;
  8.  
  9. public static class StringSanitizer
  10. {
  11.     public static string Sanitize(this string stringValue)
  12.     {
  13.         if (null == stringValue)
  14.             return stringValue;
  15.         return stringValue
  16.                     .RegexReplace("-{2,}", "-")                 // transforms multiple --- in - use to comment in sql scripts
  17.                     .RegexReplace(@"[*/]+", string.Empty)      // removes / and * used also to comment in sql scripts
  18.                     .RegexReplace(@"(;|\s)(exec|execute|select|insert|update|delete|create|alter|drop|rename|truncate|backup|restore)\s", string.Empty, RegexOptions.IgnoreCase);
  19.     }
  20.  
  21.  
  22.     private static string RegexReplace(this string stringValue, string matchPattern, string toReplaceWith)
  23.     {
  24.         return Regex.Replace(stringValue, matchPattern, toReplaceWith);
  25.     }
  26.  
  27.     private static string RegexReplace(this string stringValue, string matchPattern, string toReplaceWith, RegexOptions regexOptions)
  28.     {
  29.         return Regex.Replace(stringValue, matchPattern, toReplaceWith, regexOptions);
  30.     }
  31. }
  32.  
  33.  
  34. /*
  35.     And some tests for input strings ( C# ) ...
  36.     string query = string.Format("SELECT ServicesID, ServiceName FROM tblServices WHERE ServicesID={0} ", ServicesID.Sanitize());
  37.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement