Skip to content

Instantly share code, notes, and snippets.

@nanoDBA
Last active May 27, 2020 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nanoDBA/11bfd03f53c4815d40888695babb1b98 to your computer and use it in GitHub Desktop.
Save nanoDBA/11bfd03f53c4815d40888695babb1b98 to your computer and use it in GitHub Desktop.
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
Copy link

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

@nanoDBA
Copy link
Author

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