C# / PowerShell - Working with Windows Security Identifiers

Updated on 2/26/2015

//Function converts hexadecimal SecurityIdentifier into decimal form
private void btnHex2Dec_Click(object sender, EventArgs e)
{
	try
	{
		String hex = txtInput.Text.Replace("0x", "").Trim();

		byte[] bytes = new byte[hex.Length / 2];
		for (int x = 0; x < hex.Length / 2; x++)
		{
			bytes[x] = Byte.Parse(hex.Substring(x * 2, 2), System.Globalization.NumberStyles.HexNumber);
		}

		SecurityIdentifier sid = new SecurityIdentifier(bytes, 0);
		txtOutput.Text = sid.Value;
	}
	catch (Exception ex)
	{
		txtOutput.Text = "Error: " + ex.Message;
	}
}

//Function converts decimal SecurityIdentifier into hexadecimal form
private void btnDec2Hex_Click(object sender, EventArgs e)
{
	try
	{
		SecurityIdentifier sid = new SecurityIdentifier(txtInput.Text.Trim());

		byte[] binaryForm = new byte[sid.BinaryLength];
		sid.GetBinaryForm(binaryForm, 0);

		txtOutput.Text = BitConverter.ToString(binaryForm);
		txtOutput.Text = "0x" + txtOutput.Text.Replace("-", "");
	}
	catch (Exception ex)
	{
		txtOutput.Text = "Error: " + ex.Message;
	}
}

//Function converts base64 SecurityIdentifier to decimal
private void btnBase64_Click(object sender, EventArgs e)
{
	try
	{
		byte[] encodedDataAsBytes = System.Convert.FromBase64String(txtInput.Text.Trim());
		SecurityIdentifier sid = new SecurityIdentifier(encodedDataAsBytes, 0);
		txtOutput.Text = sid.Value;
	}
	catch (Exception ex)
	{
		txtOutput.Text = "Error: " + ex.Message;
	}
}


Here is a PowerShell equivalent to the second function (decimal SecurityIdentifier into hexadecimal)

#Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx
param ( [string]$SidString )

#Create SID .NET object using SID string provided
$sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring

# Create a byte array of the proper length
$sidBytes = New-Object byte[] $sid.BinaryLength

#Convert to bytes
$sid.GetBinaryForm( $sidBytes, 0 )

# Iterate through bytes, converting each to the hexidecimal equivalent
$hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") }

# Join the hex array into a single string for output
$hexArr -join ''

PowerShell to get a User's SID

$objUser = New-Object System.Security.Principal.NTAccount("domain", "user")
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSID.Value

Output:

S-1-5-21-2603034835-2464472188-148698776-1107 

PowerShell to get a Username from their SID

$objSID = New-Object System.Security.Principal.SecurityIdentifier ` ("S-1-5-21-2603034835-2464472188-148698776-1107")
$objUser = $objSID.Translate( [System.Security.Principal.NTAccount])
$objUser.Value

Output:

domain\user

Files

SIDConvert.zip