Powershell SecureString Encrypt / Decrypt for plain text not working

We are trying to save the user's password in the registry as a secure string, but we cannot find a way to convert it back to plain text. Is this possible with SecureString?

Here is a simple test script that we are trying to use ...

Write-Host "Test Start..." $PlainPassword = "@SomethingStupid" | ConvertTo-SecureString -AsPlainText -Force $BSTR = ` [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($PlainPassword) $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) Write-Host "Password is: " $PlainPassword Read-Host 

This is the mistake we get ...

 The term ' [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\test.ps1:4 char:71 + $BSTR = ` [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR <<<< ($PlainPassword) + CategoryInfo : ObjectNotFound: ( [System.Runtim...ureStringToBSTR:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Cannot find an overload for "PtrToStringAuto" and the argument count: "1". At C:\test.ps1:5 char:75 + $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto <<<< ($BSTR) + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodCountCouldNotFindBest 
+6
source share
2 answers

What happens with the return in the string $BSTR = ... ? I agree with Graham above. If I remove the reverse, it works fine:

 $PlainPassword = "@SomethingStupid" | ConvertTo-SecureString -AsPlainText -Force $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($PlainPassword) $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) Write-Host "Password is: " $PlainPassword 

Outputs:

 Password is: @SomethingStupid 

You are not trying to run this on something like Windows RT or another PowerShell configuration where the language is limited - you?

+13
source

Here's a kludgy, but much easier way to decrypt a secure string, using the fact that the PSCredential class has a constructor that accepts a password as a secure string and a method ( GetNetworkCredential ) that returns this password in plain text:

 (New-Object System.Management.Automation.PSCredential 'N/A', $secure_string).GetNetworkCredential().Password 

Although it is intended to be used with credentials, nothing prevents you from using it to decrypt any secure string * regardless of purpose, supplying a dummy argument for the username (the username argument cannot be empty or empty, but any meaningless string will do).


* In the context of an account encrypted with a secure string to begin with, of course
+11
source

All Articles