Functions/Convert-SecureStringTo32ByteKey.ps1

<#
    .SYNOPSIS
        Convert a secure string to a byte array.
     
    .DESCRIPTION
        Convert the supplied secure string to a 32 byte array.
     
    .PARAMETER SecureString
        A secure string object.
     
    .EXAMPLE
        Convert-SecureStringTo32ByteKey -SecureString ( ConvertTo-SecureString -String 'Pr3$haredK3y' -AsPlainText -Force )
#>

function Convert-SecureStringTo32ByteKey
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$True,Position=1)]
        [ValidateNotNullOrEmpty()]
        [System.Security.SecureString]
        $SecureString
    )

    $hasher = New-Object -TypeName System.Security.Cryptography.SHA256CryptoServiceProvider

    try
    {
        $bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)
        $hasher.ComputeHash( [System.Text.Encoding]::UTF8.GetBytes([Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr))) 
    }
    catch
    {
        throw $_
    }
    finally
    {
        [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
        $hasher.Dispose()
    }
}