DSInternals/Src/DSInternals.Common/Data/DistinguishedNameComponent.cs

88 lines
2.6 KiB
C#
Raw Normal View History

2015-12-26 22:44:43 +00:00
namespace DSInternals.Common.Data
{
using DSInternals.Common;
using System;
2016-06-18 16:30:59 +00:00
using System.Text;
2015-12-26 22:44:43 +00:00
2018-10-23 14:22:26 +00:00
public class DistinguishedNameComponent
2015-12-26 22:44:43 +00:00
{
public string Name;
public string Value;
public DistinguishedNameComponent(string name, string value)
{
Validator.AssertNotNullOrWhiteSpace(name, "name");
Validator.AssertNotNullOrWhiteSpace(value, "value");
this.Name = name;
this.Value = value;
}
public override string ToString()
{
2016-06-18 16:30:59 +00:00
return String.Format("{0}={1}", EscapeValue(this.Name), EscapeValue(this.Value));
2015-12-26 22:44:43 +00:00
}
2016-06-18 16:30:59 +00:00
private static string EscapeValue(string input)
2015-12-26 22:44:43 +00:00
{
2016-06-18 16:30:59 +00:00
var result = new StringBuilder(input.Length);
for (int i = 0; i < input.Length; i++)
2015-12-26 22:44:43 +00:00
{
2016-06-18 16:30:59 +00:00
char currentChar = input[i];
if (IsSpecialChar(currentChar))
{
// Escape special chars
result.Append('\\');
result.Append(currentChar);
}
else if (currentChar == ' ' && (i == 0 || i == input.Length - 1))
{
// Escape the leading or ending space
result.Append("\\ ");
}
else if (currentChar < 32)
{
// Escape control chars
result.AppendFormat("\\{0:X2}", (int)currentChar);
}
else if (currentChar >= 128)
{
// Escape multibyte chars
byte[] bytes = Encoding.UTF8.GetBytes(currentChar.ToString());
foreach (byte currentByte in bytes)
{
result.AppendFormat("\\{0:X2}", currentByte);
}
}
else
{
// Append the char without escaping
result.Append(currentChar);
}
2015-12-26 22:44:43 +00:00
}
2016-06-18 16:30:59 +00:00
return result.ToString();
}
private static bool IsSpecialChar(char c)
{
// RFC 2253: special = "," / "=" / "+" / "<" / ">" / "#" / ";"
switch(c)
2015-12-26 22:44:43 +00:00
{
2016-06-18 16:30:59 +00:00
case ',':
case '=':
case '+':
case '<':
case '>':
case '#':
case ';':
case '\\': // Escape char
case '"': // Quote char
return true;
default:
return false;
2015-12-26 22:44:43 +00:00
}
}
}
2018-10-23 14:22:26 +00:00
}