While hanging around the Microsoft Technet Powershell forums, I came across a question regarding having a hard-coded password for a user account to run a query against some servers. I many cases, this is never a good idea as if the script gets compromised, you could have a potential security incident on your hands. One solution that I have seen used is to encrypt your password in powershell using the ConvertFrom-SecureString cmdlet.
You need to run this as the account that is going to be running this script. Otherwise the embedded password in the script will not work! This is actually a smart idea. If any account has the ability to run the script with the embedded password and it is a domain admin level account, a malicious user could write their own code into the script to run or even decrypt the password (which I will explain how later on).
To being with this, you can use the Read-Host -AsSecure cmdlet to first get the password that you want to use. In this case, my password is going to be “password”.
Now you have a password that is saved as a secure string “System.Security.SecureString”. Unfortunately, while you can use this in the current Powershell session for authenticating to a remote server, you will not be able to hardcode this as it is into the script or a text file to read from. You must then take that secure string and convert it from the secure string to a long string of characters using ConvertFrom-SecureString.
You can then copy and paste this string into your script or text file that will be used against the account that will be used to authenticate to the server.
The only account that will be able to use this is the account that created the string. If you attempt to use this with a different account, it will error out because it will not understand what to do with the string.
Now that we have encrypted the password and passed it into a text file or a script, we will now look at how to decrypt the string using both the account that created the string and an account that is trying to read the string.
1. This is only recommended as a last resort for scripts. Hard-coding a password into a script, encrypted or not, is always a risk.
2. You must use the ConvertFrom-SecureString to put the password into a usable string to copy/paste into the script.
3. Only the account that converted the string and decrypt it and use the password for authentication.