Powershell | Secure Script Passwords

I’ve recently been configuring some more PowerShell scripts to help automate some our tasks within our domain. One thing that always seems to crop up is securing passwords that are required within the script. Like most companies we use a central server running a passwords management solution. This is great when you need to manually use passwords with day-to-day tasks but not so great when you need the password in a PowerShell script.

To help secure passwords I’ve started using key files to secure access to an additional password file which is encrypted against the key file. I’ve found this to extremely helpful as the key file can be placed on a network share which, in turn can be restricted by NTFS permissions.

Below is how I create and use this method, its not a method that will work in all scenarios but can be quite useful.

To use this method, you need three separate files although the third is the script file:

  • A Key File
  • A Password File
  • PowerShell Script File

This process works by firstly generating a key file, the key file. Secondly a Password file will be generated using the key file to secure it. The password can then be used in the script files.

Generating the key file is easy, the output will be a 256 AES encrypted file:

$KeyFile = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($KeyFile)
$KeyFile | out-file C:\PowerKeys\KeyFile.key

At this point the KeyFile.key can be moved to a network share and restricted.

Now to create the password file, you will be prompted to enter a username and password. Be sure to enter the required password for the account:

(get-credential).Password | ConvertFrom-SecureString -key (get-content C:\PowerKeys\KeyFile.key) | set-content "C:\PassKeys\PassKey.txt"

This password file will need to be located on the server it will be used by but it can also be opened with the use of the Key File so be sure to restrict the key file!

Finally add the following into your script file to populate the password:

$password = Get-Content C:\PassKeys\PassKey.txt | ConvertTo-SecureString -Key (Get-Content C:\PowerKeys\KeyFile.key)
$credential = New-Object System.Management.Automation.PsCredential("Administrator",$password)

If you were to look into the $credential variable, you’ll notice you won’t be able to see the password. This is because Windows Data Protection service is used to encrypt and decrypt the password.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.