PoshCode Archive  Artifact [e8f4a47608]

Artifact e8f4a476089743dd2cbbf8017a7e57961dcb388060c94cf3fca2d7dcc58878f4:

  • File HEX-string-to-SID-string.ps1 — part of check-in [fc0aecc32b] at 2018-06-10 14:08:26 on branch trunk — The function hex2sid will convert HEX-represented SID string like 010500000000000515000000358A021A75B9755407E53B2B1EF10108 to SID string (also known as SSDL) (user: Dormidont size: 2239)

# encoding: ascii
# api: powershell
# title: HEX string to SID string
# description: The function hex2sid will convert HEX-represented SID string like 010500000000000515000000358A021A75B9755407E53B2B1EF10108 to SID string (also known as SSDL)
# version: 0.1
# type: function
# author: Dormidont
# license: CC0
# x-poshcode-id: 6121
# x-archived: 2016-03-18T22:01:26
# x-published: 2016-11-27T21:56:00
#
# It was translated from vbscript function found on the internets
# Maybe there is a simpler way to do it but I’m dumb enough not to have found it :)
#
Function EndianReverse ($strHex)
{
 $intCounter=$strHex.length-1
 do
  { 
   $reverse=$reverse+$strHex.substring($intCounter-1, 2)
   $intCounter=$intCounter-2
  }
 until ($intCounter -eq -1)
 return $reverse
}

Function hex2sid ($strHex)
{
 $intSidVersionLength = 2
 $intSubAuthorityCountLength = 2
 $intAuthorityIdentifierLength = 12
 $intSubAuthorityLength = 8
 $intStringPosition = 0
 $bytSidVersion = [byte][convert]::ToInt32($strHex.substring($intStringPosition, $intSidVersionLength),16)
 $intStringPosition = $intStringPosition + $intSidVersionLength
 $bytSubAuthorityCount=[byte][convert]::ToInt32($strHex.substring($intStringPosition, $intSubAuthorityCountLength),16)
 $intStringPosition = $intStringPosition + $intSubAuthorityCountLength
 $lngAuthorityIdentifier=[long][convert]::ToInt32($strHex.substring($intStringPosition, $intAuthorityIdentifierLength),16)
 $intStringPosition = $intStringPosition + $intAuthorityIdentifierLength
 [string]$ConvertHexStringToSidString = "S-" + $bytSidVersion + "-" + $lngAuthorityIdentifier
 Do 
  {
   $lngTempSubAuthority = EndianReverse($strHex.substring($intStringPosition, $intSubAuthorityLength))
   $lngTempSubAuthority = [long][convert]::ToInt32($lngTempSubAuthority,16)
   $intStringPosition = $intStringPosition + $intSubAuthorityLength
   if ($lngTempSubAuthority -lt 0) 
    {
     $lngTempSubAuthority = $lngTempSubAuthority + 4294967296
    }
   $ConvertHexStringToSidString = $ConvertHexStringToSidString+"-"+$lngTempSubAuthority
   $bytSubAuthorityCount = $bytSubAuthorityCount - 1
  }
 until ($bytSubAuthorityCount -eq 0)
 return $ConvertHexStringToSidString
}