Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SID string format to bytes array

Tags:

c#

.net

sid

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.

like image 414
dev Avatar asked Dec 04 '22 06:12

dev


2 Answers

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);
like image 94
Konrad Kokosa Avatar answered Dec 28 '22 07:12

Konrad Kokosa


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.

like image 20
Jon R Avatar answered Dec 28 '22 06:12

Jon R