Converting a binary type SID to System.Security.Principal.SecurityIdentifier in PowerShell

12.6k Views Asked by At

I found a link on this website which shows how to convert a SID to the binary type. Can someone please tell me how to do the reverse - to convert a binary type back to a SID.

This is the script that was provided to go from SID to binary:

PS> $sid = New-Object System.Security.Principal.SecurityIdentifier ("S-1-5-21-105005785-2143699225-541720777-501") 
PS> $c = New-Object 'byte[]' $sid.BinaryLength 
PS> $sid.GetBinaryForm($c, 0) 

Thanks!

2

There are 2 best solutions below

2
On

To go from byte array to SID, try:

(New-Object System.Security.Principal.SecurityIdentifier($c, 0)).toString()
0
On

If you want to do the same in C# then you can do something like this (from https://stackoverflow.com/a/59258680/12508260):

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.