Seaport
Seaport

Reputation: 173

Password from SecureString makes the script hanging

$password = Get-Content 'c:\temp\tmp1\pw.dat' | ConvertTo-SecureString 
& "C:\Program Files\PuTTY\pscp.exe" -P 2222 -pw $password 'c:\temp\tmp1\test.txt' 'root@localhost:/home/root/temp'

The above code just got hanging; However, the code below worked.

$password='mypw'
& "C:\Program Files\PuTTY\pscp.exe" -P 2222 -pw $password 'c:\temp\tmp1\test.txt' 'root@localhost:/home/root/temp'

Any suggestion? I do not think I typed the password wrong since I did it several times. Furthermore, I expect an error message if the password was typed wrong. By the way, the objective of the script is to transfer the file to a linux box.

Upvotes: 0

Views: 973

Answers (1)

ArcSet
ArcSet

Reputation: 6860

As stated in a comment the .dat file is created using

read-host -AsSecureString | ConvertFrom-SecureString | out-file

So there are 2 ways I know of doing this.

$EncryptedString = read-host -AsSecureString | ConvertFrom-SecureString

$SecureString = $EncryptedString | ConvertTo-SecureString

$Pointer = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)

$PlainTextPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($Pointer)

$PlainTextPassword

The secret here is the [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString) which turns the string into a bytes and returns a pointer to where it is located

The next part [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($Pointer) goes to the pointer and turns the bytes into a string.

The other way would be turning the secure string into a PSCredential.

$EncryptedString = read-host -AsSecureString | ConvertFrom-SecureString

$SecureString = $EncryptedString | ConvertTo-SecureString

$PlainTextPassword = ([PsCredential]::new("DoesntMatter",$SecureString)).GetNetworkCredential().Password

$PlainTextPassword

This turns the Secure String into a PSCredential where you can get the NetworkCredential's password which is in plain text.

Upvotes: 2

Related Questions