Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Passing Credentials in PowerShell between users and computers using keys
## Create AES key with random data and export to file
<#
Sometimes a script needs to use a password, but you want it stored securely. Passing a credential by utilizing 2 things:
1. A password file that contains the encrypted file
2. A key file that contains a randomly generated AES key
allows for utilization of credentials within scripts by different users and servers.
**The following method is only as secure as the locations of the files(password and key) themselves.**
source:
https://www.pdq.com/blog/secure-password-with-powershell-encrypting-credentials-part-2/
video:
https://www.youtube.com/watch?v=LfFJqRW-9Ks
#>
#$KeyFile = "\\server\share\keys\aes.key"
#$Key = New-Object Byte[] 32 # You can use 16, 24, or 32 for AES
#[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
#$Key | out-file $KeyFile
#
## Create SecureString and export to file
#
#$PasswordFile = "\\server\share\keys\password.txt"
#$KeyFile = "\\server\share\keys\aes.key"
#$Key = Get-Content $KeyFile
#$Password = '$0secr3t-k33p_it_s@f3!%%%%%%%%%7ZtfcUskD2vGVrHPOaR3A5mhXI6SYxe' | ConvertTo-SecureString -AsPlainText -Force
#$Password | ConvertFrom-SecureString -key $Key | Out-File $PasswordFile
# Create PSCredential object with aes key and password file
$User = "domainname\SVCsomeServiceaccount"
$PasswordFile = "\\server\share\keys\password.txt"
$KeyFile = "\\server\share\keys\aes.key"
$key = Get-Content $KeyFile
$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString -Key $key)
<# System.Security.SecureString - secure cmdlets support passing this object property #>$MyCredential.Password
<# decrypted password - presents password as plaintext#>$MyCredential.GetNetworkCredential().Password
@Lippy1m1

This comment has been minimized.

Copy link

@Lippy1m1 Lippy1m1 commented Apr 10, 2020

Thanks for this it was helpful to me, so I wanted to say thank you.

@nanoDBA

This comment has been minimized.

Copy link
Owner Author

@nanoDBA nanoDBA commented May 27, 2020

I'm glad it was helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.