1
votes

I've been working with Powershell for quite some time now but I don't understand how the encryption works, not even sure I'm using the right syntax from reading the help files.

#Get User Information
$User = Read-Host "Please enter your username"
$Password = Read-Host "Please enter your password. This will be encrypted" -AsSecureString | ConvertTo-SecureString -AsPlainText -Force

#Define a Key File
$KeyFile = "C:\Powershell\AES.key"
$Key = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
$Key | out-file $KeyFile

#Encrypt using AES
$PasswordFile = "C:\Powershell\Password.txt"
$KeyFile = "C:\Powershell\AES.key"
$Key = Get-Content $KeyFile
$Password | ConvertFrom-SecureString | Out-File $PasswordFile

#Set credentials to be called.
$myCredentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString -Key $key)

#Open text file.
Invoke-Command -ComputerName localhost -Credential $MyCredentials -ScriptBlock{
    Invoke-Item C:\Powershell\Password.txt
    }

I received an error when running this and I'm not sure why I can't pipe this:

ConvertFrom-SecureString : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input. At C:\Powershell\Password.ps1:15 char:13 + $Password | ConvertFrom-SecureString -Key $Key | Out-File $PasswordFile + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (System.Security.SecureString:String) [ConvertFrom-SecureString], ParameterBindingException + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand

Are there any encryption experts that can help? I'm trying to simply save a password to a text file (encrypted) and then I want to use another script to call various programs using new credentials using the encrypted password, but I can't even get the encrypted password to work correctly. Thanks in advance.

1

1 Answers

2
votes

To make things simple:

To Save the Credential Object to disk:

$credential = Get-Credential
$Key = [byte]1..32
$credential.Password | ConvertFrom-SecureString -Key $Key | Set-Content c:\cred.key

To Load it back to Powershell:

$Key = [byte]1..32
$username = "type the username here"
$encrypted = Get-Content c:\cred.key | ConvertTo-SecureString -Key $Key

## Create The Credential Object:

$credential = New-Object System.Management.Automation.PsCredential($username, $encrypted)

Sure that this is not secured, because everyone who see your code can re-use the credential,

If you are not using a key at all, the credential will be encrypted with your current user, and only the current user can decrypt it back.