C# 如何在.net中将SID转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11580128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:26:08  来源:igfitidea点击:

How to convert SID to String in .net

c#.net

提问by Major Marcell

I would like to convert the SID's System.Byte[] type to a String.

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

My code:

我的代码:

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

I tried with this but it gets the values from the domain I'm currently logged in, and i need from a given domain.

我试过这个,但它从我当前登录的域中获取值,我需要从给定的域中获取值。

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

采纳答案by M Afifi

Take a look at the SecurityIdentifierclass. You can then do simple things like,

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

var sidInBytes = (byte[]) *somestuff*
var sid = new SecurityIdentifier(sidInBytes, 0);
// This gives you what you want
sid.ToString();

回答by Roachmans

This is what ive done , after some reading it seemed safer to store the value in oct. If you dont know which servers is on the other side. The code below shows how to do it to get your desired result

这就是我所做的,经过一些阅读后,将值存储在 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();
}

回答by Ramiro Mosquera

After load the property in directoryEntry ....

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

var usrId = (byte[])directoryEntry.Properties["objectSid"][0];
var objectID = (new SecurityIdentifier(usrId,0)).ToString();