Dealing with credentials in PowerShell
Whenever you write PowerShell scripts that are going to be used for automation you need to secure your credentials. The best practice is to use a service account to execute the PowerShell script and delegate whatever privileges it needs to execute. When dealing with internal systems and resources that are usually pretty easy if they all authenticate from the same ecosystem or are integrated properly. But there is instances where you need to store credentials like when working with external APIs or deattached internal system.
The solution to the problem is to encrypt the credentials so that only the service account can access them. The common, more difficult, way of doing so was to logon to the service account and encrypt a file with the credentials. That requires more privileges for the service account, like logon as more than a service for instance. So to simplify I have created a PowerShell script to create and consume the encrypted secrets your PowerShell automation needs.
This script helps you encrypt the secret and decrypt it on the other end. Its using SecureString which in turn uses the Windows Data Protection API. Probably not enough for state secrets but far better than having the credentials sit in plain text in the config file.
When you encrypt a string, which can be anything, it will be encrypted so that the consuming account can decrypt it. In this case we have a service account that will run a scheduled PowerShell script that uses an external API and we need to encrypt the API secret.
CryptMe.ps1 -PlainText "supersecretapikey" -OutputFile C:tempapikey.enc
This will prompt you for the credentials of the service account. Once provided it will run a job as that account and encrypt the output file. When you need to consume the secret in your script just call the script again with an input file.
CryptMe.ps1 -InputFIle C:tempapikey.enc
This will return the unencrypted string to be used in your script. If you try to run this with another account then the one used for the encryption you will not get any usable information back.
The script can be found @ https://github.com/kallsbo/PowerShell/blob/master/CryptMe.ps1