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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With