Powershell: Convert a string into a securestring and back to plaintext

Hi,

.Net and therefore the powershell has the ability to define a secure string. This means that the string is immediately deleted from memory if it is no longer needed.

Convert to secure string:
Either convert an existing variable:

PS D:\> $MySecurePassword=ConvertTo-SecureString -AsPlainText -Force "MyPass"

Or

PS D:\> $MyUnsecurePassVar="MyPass"
PS D:\> $MySecurePassword=ConvertTo-SecureString -AsPlainText -Force $MyUnsecurePassVar

Or read a password from command line

PS D:\> $MySecurePassword=read-host -assecurestring "Enter password"
Enter password: ******

and convert it back to plain text

PS D:\> $pPassPointer = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($MySecurePassword)
PS D:\> $DecryptedPass = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($pPassPointer)
PS D:\> # Imported: free memory
PS D:\> [System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
PS D:\> write-host "PASS:" $DecryptedPass
Advertisment to support michlstechblog.info

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.