Skip to content

Instantly share code, notes, and snippets.

@apapiccio
Created March 30, 2017 00:19
Show Gist options
  • Save apapiccio/2af1f8a1a3a85f65ddc1bb4a6dcf0226 to your computer and use it in GitHub Desktop.
Save apapiccio/2af1f8a1a3a85f65ddc1bb4a6dcf0226 to your computer and use it in GitHub Desktop.
Storing Passwords Securely for PowerShell Scripts
# Create a 32 bit random key to be used by the AES Key
$AESKey = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($AESKey)
#Collect the location to store the AES Key file
$AESKeyFilePath = Read-Host -Prompt "Please enter the full path and file name for the AES Key (e.g. C:\AESKey.txt)"
Set-Content $AESKeyFilePath $AESKey #It will over-write existing file data if already exists
#Collect the password to encrypt. It uses the -AsSecureString to hide the text then converts it back text and encrypts using the AES Key
$InputPwd = Read-Host -Prompt "Please enter the password to encrypt" -AsSecureString
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($InputPwd)
$PlainTxtPsswd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
$secureStringPwd = $PlainTxtPsswd | ConvertTo-SecureString -AsPlainText -Force
#Export Secure content to password file
$SecurePwdFile = Read-Host -Prompt "Please enter the full path and file name for the Secure Password file (e.g. C:\AppSecurePwd.txt)"
$password = $secureStringPwd | ConvertFrom-SecureString -Key $AESKey
Add-Content $SecurePwdFile $password
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment