1

PowerShell 5.1

Is there a way to take a hash or object that contains a secure string password and export it to a file for backup? And restore if needed.

$testHash=@{key1='1';secret=ConvertTo-SecureString -String 'hello world' -AsPlainText -Force}
$sHash=ConvertTo-HashString -InputObject $testHash
$sHash

$SecurePassword = ConvertTo-SecureString $sHash -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR)
$UnsecurePassword
Rod
  • 14,529
  • 31
  • 118
  • 230
  • 2
    Yeah definitely, `Export-CliXml` can do that. It also encrypts your file using DPAPI – Santiago Squarzon Mar 15 '23 at 14:59
  • Duplicate? : [Is there a way to pass serializable objects to a PowerShell script with start-process?](https://stackoverflow.com/q/34076478/1701026) – iRon Mar 15 '23 at 15:03
  • As @Santiago notes, you can use [`Export-Clixml`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/export-clixml) and [`Import-Clixml`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/import-clixml), as shown in the linked duplicate (which uses a `[pscredential]` object, but it equally works with a custom hashtable containing a `[securestring]` instance). – mklement0 Mar 15 '23 at 15:36
  • As an aside: PowerShell 5.1 (i.e. _Windows PowerShell_) by definition runs on Windows only, but for PowerShell (Core) 7+ users it's important to note that `[securestring]` - whether persisted or not - should be avoided altogether on Unix-like platforms due to lack of encryption, and even on Windows isn't recommended for new projects anymore - see [this answer](https://stackoverflow.com/a/55797281/45375). – mklement0 Mar 15 '23 at 15:40
  • Another aside: A simpler way to convert a `[securestring]` instance to its plain-text representation (which is obviously problematic from a security standpoint) is the following: `[pscredential]::new('unused', $testHash.secret).GetNetworkCredential().Password` – mklement0 Mar 15 '23 at 15:42

0 Answers0