I have a long-standing dislike of hard-coding credentials in scripts. In a production environment, it’s never a good idea to leave sensitive account passwords hard-coded in plain text in scripts. To that end, I’ve developed an easy method in PowerShell to protect sensitive information.
The functions I present below allow you to store usernames and passwords, where the passwords are encrypted, in a form that can be later decrypted inside a script. By default, only the user account that encrypted the credentials can decrypt them, and only from that same machine. It all uses native .NET stuff, so you don’t need any third-party stuff to get it working.
Where I find this most useful is for services or scheduled tasks that run as system accounts that execute PowerShell scripts. You can log into the machine as that service account, encrypt a set of credentials, then when that scheduled task runs as that service account it is able to read them.
Using the export function I show below, you can either export your credentials to an xml file on the file system, or a registry value in the Windows registry.
Here is an example:
First, save the credential to a variable and export it to an xml file:
$cred = Get-Credential username $cred | Export-PSCredential -Path c:\temp\creds.xml
This outputs the path to the xml file you created with the encrypted credentials:
Alternately, you can export to a registry key instead:
$cred = Get-Credential username $cred | Export-PSCredential -RegistryPath HKCU:\software\test -Name mycreds
In the registry, you can see your exported credentials:
The major thing that needs to be understood about this is the encryption key that is used to encrypt these credentials is tied to both the userid used to encrypt them AND the machine you encrypted from. Unless you specify a keyphrase, you cannot decrypt these credentials as another user or from another machine. The idea is if you have a script that reads these encrypted credentials, you have to log in as the user the script runs as on the machine the script runs from and encrypt them. However, as described above, if you provide a keyphrase, you can decrypt them from anywhere as any user. You just have to somehow protect the keyphrase.
Importing the credentials again is pretty simple:
$cred = Import-PSCredential -Path C:\temp\creds.xml # OR $cred = Import-PSCredential -RegistryPath HKCU:\Software\test -Name mycreds
Specifying a keyphrase involves specifying the -KeyPhrase parameter on either the import or export function.
Below is the code. Simply paste these three functions into your PowerShell session or into your script and away you go.
Note the Get-EncryptionKey function is required for both the import and export functions!