Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Sanitize input strings against SQL injection using Regex
- If SqlParameters cannot be used this is an anti-pattern that will do the job ( C# ):
- */
- using System;
- using System.Text.RegularExpressions;
- public static class StringSanitizer
- {
- public static string Sanitize(this string stringValue)
- {
- if (null == stringValue)
- return stringValue;
- return stringValue
- .RegexReplace("-{2,}", "-") // transforms multiple --- in - use to comment in sql scripts
- .RegexReplace(@"[*/]+", string.Empty) // removes / and * used also to comment in sql scripts
- .RegexReplace(@"(;|\s)(exec|execute|select|insert|update|delete|create|alter|drop|rename|truncate|backup|restore)\s", string.Empty, RegexOptions.IgnoreCase);
- }
- private static string RegexReplace(this string stringValue, string matchPattern, string toReplaceWith)
- {
- return Regex.Replace(stringValue, matchPattern, toReplaceWith);
- }
- private static string RegexReplace(this string stringValue, string matchPattern, string toReplaceWith, RegexOptions regexOptions)
- {
- return Regex.Replace(stringValue, matchPattern, toReplaceWith, regexOptions);
- }
- }
- /*
- And some tests for input strings ( C# ) ...
- string query = string.Format("SELECT ServicesID, ServiceName FROM tblServices WHERE ServicesID={0} ", ServicesID.Sanitize());
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement