28

我想将 SID 的 System.Byte[] 类型转换为字符串。

我的代码:

string path = "LDAP://DC=abc,DC=contoso,DC=com";
DirectoryEntry entry = new DirectoryEntry(path);
DirectorySearcher mySearcher = new DirectorySearcher(entry);

mySearcher.Filter = "(&(objectClass=user)(samaccountname=user1))";
results = mySearcher.FindAll();
foreach (SearchResult searchResult in results)
{
    Console.WriteLine(searchResult.Properties["ObjectSID"][0].ToString());
}

我尝试了这个,但它从我当前登录的域中获取值,并且我需要来自给定域的值。

System.Security.Principal.NTAccount(user1)
    .Translate([System.Security.Principal.SecurityIdentifier]).value
4

3 回答 3

58

看一下SecurityIdentifier类。然后你可以做一些简单的事情,比如,

var sidInBytes = (byte[]) *somestuff*
var sid = new SecurityIdentifier(sidInBytes, 0);
// This gives you what you want
sid.ToString();
于 2012-07-20T13:39:39.777 回答
1

这就是我所做的,经过一些阅读后,将值存储在 oct 中似乎更安全。如果您不知道另一侧有哪些服务器。下面的代码显示了如何做到这一点以获得您想要的结果

private static string ExtractSinglePropertyValueFromByteArray(object value)
{
    //all if checks etc has been omitted
    string propertyValue = string.Empty;
    var bytes = (byte[])value;
    var propertyValueOct = BuildOctString(bytes); // 010500....etc
    var propertyValueSec = BuildSecString(bytes); // S-1-5-...etc
    propertyValue = propertyValueSec;
    return propertyValue;
}

private static string BuildSecString(byte[] bytes)
{
    return new SecurityIdentifier(bytes,0).Value.ToString();
}

private static string BuildOctString(byte[] bytes)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < bytes.Length; i++)
    {
        sb.Append(bytes[i].ToString("X2"));
    }
    return sb.ToString();
}
于 2012-11-07T10:35:36.750 回答
1

在 directoryEntry 中加载属性后 ....

var usrId = (byte[])directoryEntry.Properties["objectSid"][0];
var objectID = (new SecurityIdentifier(usrId,0)).ToString();
于 2018-01-10T19:20:27.603 回答