How to escape a string in C#, for use in an LDAP query

前端 未结 6 603
囚心锁ツ
囚心锁ツ 2020-12-14 10:00

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

6条回答
  •  囚心锁ツ
    2020-12-14 10:40

    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();
    }
    

提交回复
热议问题