Thursday, February 02, 2012

Powershell–Convert a SecureString to plain text

How do you go about converting a SecureString object to plain text in powershell? Turns out its not through the Convert-SecureString method.

Instead, you need to perform some interop to get the plain text string.

$Pwd = read-host -assecurestring "Password:"; #returns a SecureString object

#convert the SecureString object to plain text using PtrToString and SecureStringToBSTR

$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Pwd)
$Pwd = [Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr) #$Pwd now has the secure-string contents in plain text
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) #this is an important step to keep things secure

More info:

No comments: