Powershell how to encrypt/decrypt a password

Powershell how to encrypt/decrypt a password

Why?

This guide will help you get started with encrypting passwords within PowerShell.

The first part is to encrypt a non encrypted password through CLI, you can change the logic in such a manner to prompt a popup and even a credential session popup.
After the AES key and password are encrypted you can go over to the second part and incorporate this in your PS script(s).

Thanks to the AES key you can use this encrypted password in your scheduled task where another user (e.g MSA or local/built-in account) can start the task, and you will even be able to copy this over to another server to reuse it without the need of going through step 1 again. This is especially handy when migrating or restoring a server.

How to encrypt

# Prompt you to enter the username and password
$passwordSecureString = Read-Host "Enter Password" -AsSecureString

# Define a location to store the AESKey
$AESKeyFilePath = “C:\Your\Location\aeskey.txt”

# Define a location to store the file that hosts the encrypted password
$credentialFilePath = “C:\Your\Location\credpassword.txt”

# Generate a random AES Encryption Key
$AESKey = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($AESKey)

# Store the AES Key into a file, caution this will overwrite any existing AES key file
Set-Content $AESKeyFilePath $AESKey

$password = $passwordSecureString | ConvertFrom-SecureString -Key $AESKey

Add-Content $credentialFilePath $password

How to decrypt

# Fetch encrypted password and decrypt it for use
$AESKey = Get-Content -Path “C:\Your\Location\aeskey.txt”
$pwdTxt = Get-Content -Path “C:\Your\Location\credpassword.txt”
$tempPassword = $pwdTxt | ConvertTo-SecureString -Key $AESKey

$decryptedPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::
SecureStringToBSTR((($tempPassword))))

# Use $decryptedPassword where you need it in your code

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *