Convert SID string format to bytes array
Asked Answered
T

2

6

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.

Torry answered 9/7, 2014 at 16:16 Comment(1)
Is LookupAccountSid() your code, or a built in function?Batchelder
M
15

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);
Moguel answered 9/7, 2014 at 16:21 Comment(2)
Had all but initializing the byte[]Galan
This code works only on Windows, though :-(Jelly
L
3

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 = new System.Security.Principal.SecurityIdentifier((byte[])ne.Properties["SID"].Value, 0);

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

Literature answered 10/12, 2019 at 0:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.