Sometimes I need to use a SecureString but then I’m forced to use that string in a non-secure way. Although the recommendation is not to do this, the reality is that there are many scenarios where it’s necessary. A simple example is when I need the user to enter sensitive data in the console, but then I need to use that data as plain text to pass it as a parameter to a Windows executable. This is an example of how to do it:
Param(
[Parameter(Mandatory=$True)]
[SecureString]$password
)
function Decrypt-SecureString($secureString) {
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
return [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
}
$nonSecure = Decrypt-SecureString $password