How to Encrypt and Decrypt strings with PowerShell
Updated: Feb 7, 2021
The more you code and create tools that require API Keys or Username and Passwords, it's a good idea to encrypt any credentials. I would also recommend not to upload code to an external Git server if it may contain any credentials, maybe build an internal Git server for the more sensitive code. It is also a good idea to add certificates to your PowerShell code, here is a detailed blog post (PowerShell Basics - Execution Policy and Code Signing Part 1 - BY CARLOS PEREZ) about the topic. I may create a blog post on the whole process from creating a Windows CA server, Windows SubCA, then following Carlos Perez blog detailing the process.
To start off here are the resources that I have used to create my tool:
Use case: Normally all of your PowerShell code on a network share. The code can be called by the scheduled task to run the jobs. The network share should be locked down, so only the service account has access to it. I would also recommend building a tool to run checksums on your code in case it is modified. Different systems may need to call the scripts, and it is not a good idea to have the credentials viewable just by opening the code.
The first function in the code is Get-SecureKey. This function's job is to create an AES Key that you can use to encrypt a string. By default, I coded the script to save the file to the current user's Desktop and name the file SecureKey.key.
Each time you run Get-SecureKey the function will create a new AES Key. Recommendation create an AES Key for each code/application.
Now that we have a key we can use the key to encrypt a string. Use the Protect-String function with the required parameters -AESKeyPath and -String. If you enter everything correctly, you should see the below output.
Finally within your code you can use the Unprotect-String with the required parameters -AESKeyPath and -SecureString. If everything is entered correctly, the output should look like below.
Here is an example of the whole process.