0
votes

I try to use ConvertTo- and ConvertFrom-SecureString in 2 Powershell scripts, but I've got a problem generating encrypted passwords with a dynamic profile, and then reading/deciphering them with the SAME profile on the SAME machine.

My script ask an Interactive User (IU) to type credential for a Task User (TU). The logic is to create a PSSession fot the TU inside the powershell session of the IU, to generate a secure string from a plain text (or read-host), and to convert it to regular string to export it to a file.

$scriptUser = Read-Host "Entrez le nom de l'utilisateur qui va chiffrer/utiliser le fichier de mot de passe (domain\user)"
$scriptCredential = Get-Credential -Message "Veuillez entrer le mot de passe de l'utilisateur $scriptUser" -User $scriptUser

$Crypt = New-PSSession -Credential $scriptCredential -ComputerName localhost
if ($Crypt)
{
    Enter-PSSession $Crypt
    $Texte = "JULIEN"
    ConvertTo-SecureString $Texte -AsPlainText -Force | ConvertFrom-SecureString | Set-Content -Path C:\PathToFile\testcrypt_adm_task.txt
    Exit-PSSession
}

But when I try to read the content of the file using ConvertFrom-SecureString with the TU (interactive or task scheduler): no way!

> PS C:\PathToFile> Get-Content .\testcrypt_adm_task.txt |
> convertto-securestring convertto-securestring : Key not valid for use
> in specified state. At line:1 char:40
> + Get-Content .\testcrypt_adm_task.txt | convertto-securestring
> +                                        ~~~~~~~~~~~~~~~~~~~~~~
>     + CategoryInfo          : InvalidArgument: (:) [ConvertTo-SecureString], CryptographicException
>     + FullyQualifiedErrorId : ImportSecureString_InvalidArgument_CryptographicError,Microsoft.PowerShell.Commands.Conv    ertToSecureStringCommand

If I do the exact same command with my IU, no problem, as if the key used to encrypt my Securestring was bound to my IU and not my TU.

The point is I've got a problem really understanding what is really loaded with PSSession, as the secure-string is readable by my IU and not my TU, even if the encryption operation has been done in a PSSession with the TU creds...

Doesn't Enter-PSSession mean to really enter a session, with all the environment with it ? Is there something I am missing concerning the environment loaded with Enter-PSSession ?

Thanks for your help

2

2 Answers

0
votes

Import-clixml is the only way to save a PowerShell object to disk. Export-clixml will let you import the file into a PowerShell object.

Try changing "| Set-Content -Path C:\PathToFile\testcrypt_adm_task.txt" to "| Export-Clixml -Path C:\PathToFile\testcrypt_adm_task.txt"

When you ready to read it use $mysavedpassword = import-clixml c:\PathToFile\testcrypt_adm_task.txt

0
votes

Probably you created the secure-string using some different user and trying to covert back to plain text using different user. Please use the same user for making it secure and convert it back to plain text.