Private/Share/ConvertFrom-SecretSharingBigIntegerToByte.ps1
|
function ConvertFrom-SecretSharingBigIntegerToByte { <# .SYNOPSIS Converts a non-negative BigInteger to a big-endian byte array of an exact requested length. .DESCRIPTION Mirrors Python's int.to_bytes(length, "big"): throws if Value does not fit in Length bytes, rather than silently truncating. Built on the little-endian, signed BigInteger.ToByteArray() available on both Windows PowerShell 5.1 and PowerShell 7 (the isBigEndian/isUnsigned overload is .NET Core 3.0+ only) - strips ToByteArray()'s extra sign-preservation zero byte when present, then pads or reverses to produce exactly Length big-endian bytes. #> [CmdletBinding()] [OutputType([byte[]], [System.Object[]])] param( [Parameter(Mandatory)] [System.Numerics.BigInteger]$Value, [Parameter(Mandatory)] [ValidateRange(0, [int]::MaxValue)] [int]$Length ) $littleEndian = $Value.ToByteArray() if ($littleEndian.Count -gt $Length -and $littleEndian[$littleEndian.Count - 1] -eq 0) { $littleEndian = $littleEndian[0..($littleEndian.Count - 2)] } if ($littleEndian.Count -gt $Length) { throw "Value does not fit in $Length bytes." } if ($littleEndian.Count -lt $Length) { $littleEndian = [byte[]]($littleEndian + [byte[]]::new($Length - $littleEndian.Count)) } [array]::Reverse($littleEndian) return , $littleEndian } |