Is there a way I can encrypt a text file containing a password, store it on a Windows VM, and use it in a Powershell script to create a PSCredential?

Viewed 411

Title says it all, really. I'd like to be able to create a text file that only contains a password, encrypt the file, store it on a server, and then create a Powershell script that can look at the file and create a PSCredential object using the password in the file?

1 Answers

Starting from a known unencrypted value, you would create a SecureString, convert that to an encrypted string, and write it to a file. Then reverse the process to decrypt it:

# 1. Start with plain text (this is an example I don't expect you to store these values here!)
$user = "myUser"
$plainSecret = "mySecret"
# 2. Convert to SecureString
$secureSecret = ConvertTo-SecureString -String $plainSecret -AsPlainText -Force
# 3. Convert to encrypted string (using a key I made up - you'll want to do better, but this illustrates the point - I do not expect you to store these values here!)
$encryptedKey = @(102, 200, 12, 33, 6, 253, 21, 88, 144, 0, 0, 233, 202, 112, 41, 67) 
$encryptedSecret = ConvertFrom-SecureString -SecureString $secureSecret -Key $encryptedKey
# 4. Write that to a file
$encryptedSecret | Set-Content securesecret.txt
# 5. Now get the value back (read the file, decrypt into SecureString)
$decryptedSecret = Get-Content securesecret.txt | 
  ConvertTo-SecureString -Key $encryptedKey 
# 6. Create a credential
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $myUser, $decryptedSecret
Related