Monday, February 1, 2021

Encrypt and Decrypt your password in your Powershell script.


Powershell is not a precompiled type of language.  So therefore, anyone can read the contents of the script.  What if you need to use a password to have the script access certain resources?  You can always encrypt your password as a secured string and then decrypt it at runtime.  First you will need to encrypt your password using the code below.

$password = Read-Host -Prompt 'Enter your password to encrypt' -AsSecureString

Then, you will need to dump the output of the secure string into an xml file where you powershell script will call at runtime and decrypt.

$password | Export-Clixml -Path 'C:\securepassword.xml'

You can see that the contents of the file it create, securepassword.xml, has your password in encrypted format.

Next, have you powershell call that file and decrypt it.

$password = Import-CliXml -Path 'c:\securepassword.xml'
$plain_password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
write-host $plain_password

One caveat is that you must run the Import-CliXml command as the same user you use to encrypt the password.

No comments:

Post a Comment

Thank you for your comment.