Generate Encrypted AES string

1 minute read

Encrypting Service Account Passwords

This script will generate a Secure String Object encrypted using an AES key.

You can output the string to a file or use it as a variable in a script that you decrypt using the AES.key


<#
    .SYNOPSIS
        Generate Secure String Password Object using AES key  
    .DESCRIPTION
        Creates an encrypted AES password string using AES.key file
 
        You can use the generated string in a script:
            $encPassword = <encrypted secure string output>
            $key = get-content $keyFile
            $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList <username>, ($encPassword | ConvertTo-SecureString -Key $key)
 
    .PARAMETER keyFile
        The file to read the AES key from.  This is a mandatory parameter.
    .EXAMPLE
        GenerateSecureStringObject.ps1 -keyFile c:\tmp\keyfile.key
        Specify keyFile location and filename to read from      
#>
 
param(
    [Parameter(Mandatory=$true)][String]$keyFile
)
 
cls
 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 
 
function Show-Menu
{
     param (
           [string]$Title = 'My Menu'
     )
     cls
     Write-Host "================ $Title ================"
      
     Write-Host "C: Copy encrypted string to clipboard"
     Write-Host "S: Show encrypted string"
     Write-Host "W: Write encrypted string to file"
     Write-Host "Q: Press 'Q' to quit."
}
 
$key = Get-Content $keyFile
$password = Read-Host -AsSecureString -Prompt "`nEnter Password to Encrypt"
$encString = $password | ConvertFrom-SecureString -Key $key
 
do {
    Show-Menu -Title "String has been Encrypted"
    $input = Read-Host "Please make a selection"
    switch ($input) {
        'C'{
            [Windows.Forms.Clipboard]::SetText($encString)
            Write-Host "`nString copied to clipboard" -ForegroundColor Cyan
        }
        'S' {
            Write-Host `n$encString`n -ForegroundColor Magenta
        }
        'W' {
            $encString | Out-File (Read-Host -Prompt "`nEnter file path and name")
        }
        'Q'{
            return
        }
    }
    pause
}
until ($input -eq 'q')