PoshCode Archive  Artifact [7c88c82d44]

Artifact 7c88c82d4445fc4db47239d28a6a584377a860daab57427547ae9487664bafe0:

  • File HEX-string-to-SID-string.ps1 — part of check-in [0c700029b3] at 2018-06-10 13:21:45 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: 3181
# x-archived: 2017-02-05T12:23:38
# x-published: 2012-01-22T23:58: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
}