I have an LDAP query, which I am using to perform a search in C#. It uses two string variables (username and domain) which need to be escaped for security reasons.
H
The following is my translation from the Java code mentioned by Sophia into C#.
///
/// Escapes the LDAP search filter to prevent LDAP injection attacks.
///
/// The search filter.
///
///
/// The escaped search filter.
private static string EscapeLdapSearchFilter(string searchFilter)
{
StringBuilder escape = new StringBuilder(); // If using JDK >= 1.5 consider using StringBuilder
for (int i = 0; i < searchFilter.Length; ++i)
{
char current = searchFilter[i];
switch (current)
{
case '\\':
escape.Append(@"\5c");
break;
case '*':
escape.Append(@"\2a");
break;
case '(':
escape.Append(@"\28");
break;
case ')':
escape.Append(@"\29");
break;
case '\u0000':
escape.Append(@"\00");
break;
case '/':
escape.Append(@"\2f");
break;
default:
escape.Append(current);
break;
}
}
return escape.ToString();
}