I'm playing around with some different concepts with credential encryption so it can be passed securely through the script. If you have anything related you would like to share, I look forward to see what you can come up with. Here is what I have been playing with.


CLS

function Create-AesManagedObject($key, $IV)
{
$aesManaged = New-Object "System.Security.Cryptography.AesManaged"
$aesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC
$aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::Zeros
$aesManaged.BlockSize = 128
$aesManaged.KeySize = 256

if ($IV)
{
if ($IV.getType().Name -eq "String")
{
$aesManaged.IV = [System.Convert]::FromBase64String($IV)
}
else
{
$aesManaged.IV = $IV
}
}

if ($key)
{
if ($key.getType().Name -eq "String")
{
$aesManaged.Key = [System.Convert]::FromBase64String($key)
}
else
{
$aesManaged.Key = $key
}
}

$aesManaged
}

function Create-AesKey()
{
$aesManaged = Create-AesManagedObject
$aesManaged.GenerateKey()
[System.Convert]::ToBase64String($aesManaged.Key)
}

function Encrypt-String($key, $unencryptedString)
{
$bytes = [System.Text.Encoding]::UTF8.GetBytes($unencryptedString)
$aesManaged = Create-AesManagedObject $key
$encryptor = $aesManaged.CreateEncryptor()
$encryptedData = $encryptor.TransformFinalBlock($bytes, 0, $bytes.Length);
[byte[]] $fullData = $aesManaged.IV + $encryptedData
$aesManaged.Dispose()
[System.Convert]::ToBase64String($fullData)
}

function Decrypt-String($key, $encryptedStringWithIV)
{
$bytes = [System.Convert]::FromBase64String($encryptedStringWithIV)
$IV = $bytes[0..15]
$aesManaged = Create-AesManagedObject $key $IV
$decryptor = $aesManaged.CreateDecryptor();
$unencryptedData = $decryptor.TransformFinalBlock($bytes, 16, $bytes.Length - 16);
$aesManaged.Dispose()
[System.Text.Encoding]::UTF8.GetString($unencryptedData).Trim([char]0)
}

$key = Create-AesKey
$key

$salt = ( -join ((0x30..0x39) + ( 0x41..0x5A) + ( 0x61..0x7A) | Get-Random -Count 128 | % {[char]$_}) )
$salt

$credentials = Get-Credential

#Append salt hash to our credentials prior to encryption to make it more secure
$password = $salt + $credentials.password
$user = $salt + $credentials.UserName

#Encrypt the credentials
$encryptedPass = Encrypt-String $key $password
$encryptedUser = Encrypt-String $key $user

#Decrypt the credentials
$backToPlainTextA = Decrypt-String $key $encryptedUser
$backToPlainTextB = Decrypt-String $key $encryptedPass

#Output the Encrypted Password
$encryptedUser
$encryptedPass

#Output the Decrypted Password
$backToPlainTextA -replace $salt,""
$backToPlainTextB -replace $salt,""