Secure string vs. encrypted standard string

Can someone help me in understanding the difference between a secure string and an encrypted standard string?

From the PowerShell help: “The ConvertFrom-SecureString cmdlet converts a secure string (System.Security.SecureString) into an encrypted standard string (System.String). Unlike a secure string, an encrypted standard string can be saved in a file for later use.”

Ok. So I create a PSCredential object which contains a password as a secure string:

$PasswordAsSecureString = Read-Host "Enter password for $UserName" -AsSecureString
$PSCredential = New-Object System.Management.Automation.PSCredential $UserName, $PasswordAsSecureString

Then I use Export-Clixml and save it to disk. Huh? Didn’t they mentioned this cannot be done?

Let’s try something different: I convert the secure string into an encrypted standard string and display it on the screen:

$EncryptedPassword = $PasswordAsSecureString | ConvertFrom-Securestring

Then I open the XML-file from above and compare both strings - and they are actually IDENTICAL!

If both strings are the same, then I don’t understand the difference. Or is one of them converted automatically, e.g. by saving it into a file? Then what do I need the ConvertFrom/ConvertTo-SecureString cmdlets for?

Export-CliXml will do the conversion for you. ConvertFrom-SecureString is mainly if you want to write your own file output (via Add-Content, Out-File, or whatever).

Thx a lot, now I have a better understanding!

Btw. Import-CliXml does the conversion as well, so you can read and write PSCredential objects directly without having to deal with the string conversions.

Since the encryption is based on DPAPI based on the user’s context and the machine the SecureString was created on, it can be handy to know where that happened. You can add a NoteProperty as an FYI before you export it as XML.

$PSCredential | Add-Member -NotePropertyName Origin -NotePropertyValue $env:COMPUTERNAME

Great idea - I’ll Keep that in mind! And this technique might come in handy in other situations as well. Many thanks!