How to store script credentials securely

Have you ever wonder how to store script credentials securely ? If no, in todays article I want to explain you how to do it.

Frequent tenedency of PowerShell programmers is storing plain text password inside one of the variable of the script.
Of course it’s HUGE MISTAKE!
Even if credentials are provided via prompt from Get-Credential command, password is not very secure.

To ensure that is not safe check below command.

$Credential = Get-Credential
$CredentialPassword = $Credential.GEtNEtworkCredential().Password
Write-Host "Isn't your password? $CredentialPassword"

Recommended solution which should be used in the script is to export secure string to readable format into file.
Below script export password to file.

$password = "MySuperSecretPassword"
$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force
$secureStringText = $secureStringPwd | ConvertFrom-SecureString 
Set-Content "C:\temp\MySuperSecretPassword.txt" $secureStringText

These cmdlets use the Windows Data Protection API (DPAPI) to generate an AES key based-on the current user’s password (ie. the user context you’re running Powershell under) and use this to encrypt the password in the file.

There is also an option to provide a specific AES Key for it to use to perform the encryption instead

$AESKey = New-Object Byte[] 32
Set-Content "C:\temp\MySuperSecretAESKey.txt" $AESKey	
$password = $passwordSecureString | ConvertFrom-SecureString -Key $AESKey
Add-Content $credentialFilePath $password

If password will be encrypted by another AES Key like on example below, remember to decrypt password using below method

$AESKey = Get-Content C:\temp\MySuperSecretAESKey.txt
$Password = Get-Content C:\temp\MySuperSecretPassword.txt
$SecurePassword = $pwdTxt | ConvertTo-SecureString -Key $AESKey

I hope it will be usefull for some of you 🙂

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.