public/ConvertTo-GzUnprotectedByte.ps1
if($null -eq (Get-Command ConvertTo-GzUnprotectedByteArray -EA SilentlyContinue)) { function ConvertTo-GzUnprotectedByteArray() { <# .SYNOPSIS Converts a secure string to byte[] .DESCRIPTION Converts a secure string to a byte array using the specified Encoding. .PARAMETER SecureString The secure string to pass in. .PARAMETER Encoding The string encoding to use for converting to bytes. .EXAMPLE PS C:\>$bytes = $ss | ConvertTo-GzUnprotectedByteArray .INPUTS .OUTPUTS Byte[] .NOTES Its better to convert a security string to an array of chars or array of bytes rather than a string. #> Param( [Parameter(Position = 0, ValueFromPipeline = $true)] [SecureString] $SecureString, [String] $Encoding = "UTF-8" ) $enc = [System.Text.Encoding]::GetEncoding($Encoding) $bstr = [IntPtr]::Zero; $charArray = New-Object 'char[]' -ArgumentList $SecureString.Length try { $bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString); [System.Runtime.InteropServices.Marshal]::Copy($bstr, $charArray, 0, $charArray.Length); $bytes = $enc.GetBytes($charArray); return $bytes } finally { [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr); } } } |