Wednesday, May 15, 2019

Powershell: Securely pass credentials to script

Embedding user credential on the Powershell script is sometimes regarded as security breach, and severely punished when it was revealed.
It would be better solution to use ConvertFrom-SecureString to encrypt secure string, and ConvertTo-SecureString to decrypt.

Overall steps would be like following:
1. Create password with 'Secure string object'.
2. Create encrypted password file with [1] by 'ConvertFrom-SecureString' cmdlet.
3. Decrypt [2] file to get password as 'Secure string object' by runnning 'ConvertTo-SecureString' cmdlet.


#Create password as 'Secure string object'
> $password=Read-Host -AsSecureString "Enter Password"
Enter Password: ***********

#You can see the password you typed became 'Secure string object'
> $password
System.Security.SecureString

#Save 'Secure string object' with encryption
> $password | ConvertFrom-SecureString | Out-File password-file.txt

#You can see the password was encrypted and sotred in file
> cat .\password-file.txt
01000000d08c9ddf0115d1118c7a00c04fc297eb0100000052be3e1d12e24643a99e5adca0fccae300000000020000000000106

#Now you can decrypt the password-file and can be used for credential.
> $User = "somedomain\yangjie"
> $PWord = Get-Content .\password-file.txt | ConvertTo-SecureString
> $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord

No comments:

Post a Comment