PoshCode Archive  Artifact [16646d904a]

Artifact 16646d904ada3f7fcc66c78993327f5555b6a30e50885e2360a9829213752f0c:

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

# 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: 931819
# license: CC0
# x-poshcode-id: 5802
# x-archived: 2015-04-03T06:21:28
# x-published: 2015-04-01T15:19: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
}