How to escape a string in C#, for use in an LDAP query(如何在 C# 中转义字符串以用于 LDAP 查询)
问题描述
我有一个 LDAP 查询,我用它在 C# 中执行搜索.它使用两个字符串变量(用户名和域),出于安全原因需要对其进行转义.
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.
我应该如何转义字符串?C#.NET 中是否有可用的函数来执行此操作?
How should I escape the strings? Is there a function available in C#.NET to do this?
LDAP 搜索条件示例:
Example LDAP search conditions :
(objectCategory=person)
(userprincipalname=username@domain*)
(samaccountname=username)
C# 中的示例 LDAP 查询字符串:
Example LDAP query string in C# :
string search = "(&(&(objectCategory=person)(userprincipalname="
+ username
+ "@"
+ domain
+ "*)(samaccountname="
+ username
+ ")))";
我已经有 LDAP 查询工作,并返回结果.我想要的只是转义参数.
I already have the LDAP query working, and returning results. All I want is to escape the parameters.
推荐答案
以下是我将Sophia提到的Java代码翻译成C#.
The following is my translation from the Java code mentioned by Sophia into C#.
/// <summary>
/// Escapes the LDAP search filter to prevent LDAP injection attacks.
/// </summary>
/// <param name="searchFilter">The search filter.</param>
/// <see cref="https://blogs.oracle.com/shankar/entry/what_is_ldap_injection" />
/// <see cref="http://msdn.microsoft.com/en-us/library/aa746475.aspx" />
/// <returns>The escaped search filter.</returns>
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(@" 0");
break;
case '/':
escape.Append(@"2f");
break;
default:
escape.Append(current);
break;
}
}
return escape.ToString();
}
这篇关于如何在 C# 中转义字符串以用于 LDAP 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C# 中转义字符串以用于 LDAP 查询
基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 将数据集转换为列表 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
