Powershell Security : Authenticate a Script Using an Encrypted Password

Powershell Security : Authenticate a Script Using an Encrypted Password

·

2 min read

Rather than saving a username and password in plain-text within a powershell script, a more secure way of authenticating is by passing auth credentials using an encrypted password file. Should someone get a hold of this password file they can open it but not read the actual data/password. Additionally, this generated password file is only usable when invoked from the machine it was created on.

In the example below, the script authenticates from one windows server to another using the encrypted password file, runs an ipconfig command (to generate output), and then writes the results to the log file.

<# Powershell Security : Authenticate script using encrypted password

Assumed Demo Environment
Demo Script Name -> myScript.ps1 
Script Location -> C:\Scripts\
Script Logs Location -> C:\Scripts\Logs\
Encrypted Password Location -> C:\Scripts\Password\
Auth Example Username -> myLogin@myDomain.local 
(can also use a local account)
Auth Password File -> myScriptAuth.txt
Script Authenticating from -> Windows Server #1
Script Authenticating to -> Windows Server #2
#>

<# Using Powershell - Create/Modify Encrypted Password File

On Windows Server #1 run the following powershell command.
Note: The output .txt file generated is only valid for scripts run from this machine.
(keep all quotes in command)
#>

"enter-secure-password-here" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Scripts\Password\myScriptAuth.txt"

# Globals

Start-Transcript -Append "C:\Scripts\Logs\myScriptAuth_Log.txt"
$ErrorActionPreference = 1
$currentTime = Get-Date -format "dd-MMM-yyyy HH:mm:ss"

# Authenticate to Remote Server

Write-Host ===== Script Start -> $currentTime ============================================ 
$authFile = "C:\Scripts\Password\myScriptAuth.txt"
$securePassword = Get-Content $authFile | ConvertTo-SecureString
$sftpcredentials = New-Object System.Management.Automation.PSCredential ("myLogin@myDomain.local", $securePassword)

# Run ipconfig command to view networking config

ipconfig /all

# Write logfile and close script

Write-Host ===== Script End -> $currentTime ============================================
Stop-Transcript
Get-ChildItem -path "C:\Scripts\Logs\" -recurse -include @("*.txt") | rename-item -newname { $_.name  -replace "_Log",($_.CreationTime.toString("yyyyMMdd-hhmmss"))}
exit

Did you find this article valuable?

Support GGG by becoming a sponsor. Any amount is appreciated!