1

I'm having some trouble creating a Powershell credential. I am reading an encrypted string from a file, converting the string to a securestring and using that to create the credential. The error I get is:

New-Object : Cannot convert argument "1", with value: "System.Security.SecureString", >for "PSCredential" to type "System.Security.SecureString": "Cannot convert >the "System.Security.SecureString" value of type "System.RuntimeType" to >type "System.Security.SecureString"."

Here is the code I'm using:

$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "athenpoly", $(Read-EncString F:\Scripting\1-Dev\RSA\p_ftp_dellpoly.rsa)


Function Read-EncString {
    param ([String]$InputFile)

    $encrypted = Import-Clixml $InputFile

    $key = (3,42,5,77,67,12,76,9,8,9,4,5,6,55,32,81,23,12,3,55,2,9,6,1,5,32,4,55,6,8,56,12)

    $csp = New-Object System.Security.Cryptography.CspParameters
    $csp.KeyContainerName = "SuperSecretKeyContainer"
    $csp.Flags = $csp.Flags -bor [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore
    $rsa = New-Object System.Security.Cryptography.RSACryptoServiceProvider -ArgumentList 5120,$csp
    $rsa.PersistKeyInCsp = $true

    $password = [char[]]$rsa.Decrypt($encrypted, $true) -join "" | ConvertTo-SecureString -Key $key 
}

Any idea what I am doing wrong?

Nick
  • 4,302
  • 2
  • 24
  • 38
mack
  • 2,715
  • 8
  • 40
  • 68

1 Answers1

1

Here is how I set a credential when reading from a file:

$PassSec = ConvertTo-SecureString $($Pass) -AsPlainText -Force
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $($Domain + "\" + $User),$passSec

Breakdown:

1. $Pass    ->  Password that is imported (Example: P@ssw0rd)
2. $Domain  ->  Domain name (Example: Contoso)  
3. $User    ->  User Name (Example: Admin)  

What this does is create the variable $cred with the username as Contoso\Admin with a password of P@ssw0rd. This ends up with the same things as the command:

$Cred = Get-Credentials "Contoso\Admin"

Only without the prompt.

Nick
  • 4,302
  • 2
  • 24
  • 38