I want to decode the password from a System.Security.SecureString to a readable password.
$password = convertto-securestring "TestPassword" -asplaintext -force
$credentials = New-Object System.Net.NetworkCredential("TestUsername", $password, "TestDomain")
This code part works fine, I can use the $credentials object. But later in my code I need the password in a readable format. Because a methode needs the password in readable string. So I must decode the password back.
How it is possible to decode the password from the $credentials object?
Update
Not working:
$password = convertto-securestring "TestPassword" -asplaintext -force
$credentials = New-Object System.Net.NetworkCredential("TestUsername", $password, "TestDomain")
$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($credentials.password)
$result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
$result
Here you go:
P@ssw0rd
The details are explained http://blogs.msdn.com/b/besidethepoint/archive/2010/09/21/decrypt-secure-strings-in-powershell.aspx
and I have yet another slightly different way of doing it.
P@ssw0rd
For a "System.Net.NetworkCredential" object, all you need to do is read the String password.
If you end up with a PSCredential object, from an interactive command like Get-Credential use
See http://blogs.technet.com/b/heyscriptingguy/archive/2013/03/26/decrypt-powershell-secure-string-password.aspx for details.
Note: I used PS 4 for this example.