functions/public/ConvertFrom-SodiumString.ps1

function ConvertFrom-SodiumString {
    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [AllowEmptyString()]
        [string]$InputObject,

        [Parameter(Mandatory)]
        [object]$Key
    )

    begin {
        Initialize-SodiumType
        $keyBytes  = Resolve-SodiumKey -Key $Key
        $minLength = [PSSodium.Sodium]::NonceBytes + [PSSodium.Sodium]::MacBytes
    }

    process {
        $rawBytes = [System.Convert]::FromBase64String($InputObject)
        if ($rawBytes.Length -lt $minLength) {
            $PSCmdlet.ThrowTerminatingError(
                [System.Management.Automation.ErrorRecord]::new(
                    [System.Exception]::new("Input too short: need at least $minLength bytes, got $($rawBytes.Length)"),
                    'SodiumInputTooShort',
                    [System.Management.Automation.ErrorCategory]::InvalidArgument,
                    $InputObject))
        }

        $nonce      = [byte[]]::new([PSSodium.Sodium]::NonceBytes)
        $ciphertext = [byte[]]::new($rawBytes.Length - [PSSodium.Sodium]::NonceBytes)
        [System.Buffer]::BlockCopy($rawBytes, 0,                             $nonce,      0, $nonce.Length)
        [System.Buffer]::BlockCopy($rawBytes, [PSSodium.Sodium]::NonceBytes, $ciphertext, 0, $ciphertext.Length)

        $plaintext = [byte[]]::new($ciphertext.Length - [PSSodium.Sodium]::MacBytes)
        $rc = [PSSodium.Sodium]::crypto_secretbox_open_easy(
            $plaintext, $ciphertext, [ulong]$ciphertext.Length, $nonce, $keyBytes)
        if ($rc -ne 0) {
            $PSCmdlet.ThrowTerminatingError(
                [System.Management.Automation.ErrorRecord]::new(
                    [System.Exception]::new('Decryption failed: MAC verification error. Wrong key or corrupted data.'),
                    'SodiumMacVerificationFailed',
                    [System.Management.Automation.ErrorCategory]::InvalidData,
                    $InputObject))
        }

        [System.Text.Encoding]::UTF8.GetString($plaintext)
    }
}