In the Windows world PowerShell is a wannabe Linux terminal.
In some situations it is really useful but sometimes it may be a big pain in the ass.
Today we will see how we can secure credentials in a PowerShell script. We have 2 options to do this, first is to ask for credentials on script run but sometimes this is not possible so we will use second option which will convert our plain text password in a SecureString as Windows name it.
Option 1: Ask for credentials at run time
When we run the following 2 commands we will be prompted for data input:
$username = Read-Host "Enter Username"
$password = Read-Host "Enter Password" -AsSecureString

Using AsSecureString option input text will be treat as password and will replace text typed with stars.
Option 2: Use SecureString option
SecureString class represents text that should be kept confidential, such as by deleting it from computer memory when no longer needed.
We will need to generate a AES key to make SecureStrings works. You need to protect this key as best as you can since anybody who have this AES key can now decrypt protected data.
Now we will create a 16 byte AES key with random data and export to file:
$KeyFile = "\\Server1\Your_path\AES.key"
$Key = New-Object Byte[] 16 # Here can be used 16, 24, or 32 for AES
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
$Key | out-file $KeyFile
Then we need to create a SecureString object:
$PasswordFile = "\\Server1\Your_path\Password.txt"
$KeyFile = "\\Server1\Your_path\AES.key"
$Key = Get-Content $KeyFile
$Password = "Pa$$w0rd1" | ConvertTo-SecureString -AsPlainText -Force
$Password | ConvertFrom-SecureString -key $Key | Out-File $PasswordFile
The final step is creating PSCredential object:
$User = "Username"
$PasswordFile = "\\Server1\Your_path\Password.txt"
$KeyFile = "\\Server1\Your_path\AES.key"
$key = Get-Content $KeyFile
$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString -Key $key)
Now you will be able to use this key file to decrypt the password file from any machine with any user. Anyone who can read your AES key can now decrypt everything encrypted with it.
0 Comments