Wednesday 5 May 2021

Storing and Using Encrypted Passwords with Powershell

There are lots of reasons why a username and password may be incorporated into a Powershell script - naturally, the quickest and easiest way to do this is to simply store the username and password in a script using a couple of variables such as;

$username = "user1"
$password = "password1"

Simple, and it works, but is definitely not secure.

There is a simple method you can use though to encrypt the password using powershell and store it as a text file on your computer. The password is encrypted using the currently logged in windows account that is running the powershell script (when you encrypt it) so keep this in mind if you are trying to decrypt the password with a different user account (because it won't work).

This is of course a 2 step process. The first step is to take your unsecured password (yourpassword) then encrypt it, and store the encrypted text value into a txt file (in C:\temp\user1-secpw.txt)

#Store Secure Credentials 
$unsecpw = "yourpassword"
$secpw = $unsecpw | convertto-securestring -asplaintext -force
$securestringtext = $secpw | convertfrom-securestring
set-content "C:\temp\user1-secpw.txt" $securestringtext

Once you've done this part and you have your password stored in the txt file, you should at the very least clear the value from the $unsecpw if you are saving this script - otherwise you're essentially defeating the purpose of encrypting it in the first place.

The second part is of course the process of importing the txt file into a new script so you can use the password. As previously mentioned, you will only be able to decrypt the password if you are executing the decryption commands under the same user security context (ie. windows user) as when you encrypted it.

$pwd = get-content "C:\temp\user1-secpw.txt" | convertto-securestring
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd)
$Unsecpw = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

Your password is now available to use via the $unsecpw variable

No comments:

Post a Comment