Convert SID string format to bytes array

廉价感情. 提交于 2020-01-15 07:09:12

问题


I want to convert SID string format to bytes array representation which in turn will be supplied to LookupAccountSid() method's second argument in C#. But I don't find any particular in built function which can do this. For example:

SID = S-1-5-32-544

can be converted into:

(SID: 1,2,0,0,0,0,0,5,32,0,0,0,32,2,0,0)

I saw it in some posts. but how? Is there a easy way to achieve this? Basically I want the byte array representation of the NT Authority\NetworkService which is SID = S-1-5-20. Thanks in advance for your help.


回答1:


You should use SecurityIdentifier object from System.Security.Principal namespace:

var sid = new SecurityIdentifier("S-1-5-32-544");
byte[] bytes = new byte[sid.BinaryLength];
sid.GetBinaryForm(bytes, 0);

and if you want it as a text, you can then:

string strsid = string.Format("(SID: {0})", string.Join(",", bytes ));

which produces exactly:

(SID: 1,2,0,0,0,0,0,5,32,0,0,0,32,2,0,0)

Moreover, if you want SID of NT Authority\NetworkService, you can replace first line with:

var sid = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null);



回答2:


Just for reference, if you want to go the other way (byte[] to SID) it's this. In my case, the byte[] came from a ManagementEventWatcher:

ManagementBaseObject ne = e.NewEvent;
var securityIdentifier = System.Security.Principal.SecurityIdentifier((byte[])ne.Properties["SID"].Value, 0);

You can just use securityIdentifier.ToString() to get the SID as a string.



来源:https://stackoverflow.com/questions/24658845/convert-sid-string-format-to-bytes-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!