powershell, security,

Get password from Securestring

agowa338 agowa338 Aug 15, 2016 · 1 min read
Share this

Getting the password from a secure string is not always easy. If you have a PSCredential object however it is most of the times as simple as:

 $credential = Get-Credential $insecurePlainPassword =
  $credential.GetNetworkCredential().password 

If you however read that credentials from a CLIXML file or if you only got a securestring it is a bit different:

  [System.Net.NetworkCredential]::new([String]::Empty, $SecurePassword).Password
  

PowerShell 7 and above have a command for this:

  #Requires -Version 7.0 $UnsecurePassword = ConvertFrom-SecureString
  -SecureString $SecurePassword -AsPlainText 

Another way is to use marshalling to some unmanaged code functions. Most pages use PtrToStringAuto, but that is incorrect and only works for specific system configurations. It also breaks when moving between different PowerShell versions. Also most of these don't properly free the memory again and therefore cause memory leaks. dotNet won't help us here as we go into unmanaged code and dotNet doesn't know about that. Anyway, the correct way for that is:

 [SecureString]$SecurePassword =
  ConvertTo-SecureString $PlainPassword -AsPlainText -Force [IntPtr]$BSTR =
  [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
  [String]$UnsecurePassword =
  [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($BSTR)
  [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR) Remove-Variable -Name
  "BSTR" 

agowa338
Written by agowa338