Eureka Moment Wiki

One eureka moment at the time

User Tools

Site Tools


windows:scripting:ps_ss

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

windows:scripting:ps_ss [2017/08/10 13:00] (current)
Line 1: Line 1:
 +====== Powershell: Using Secure String in scripts ======
 +First create a key which will be used to encrypt the plain text password
 +<code powershell Create key>
 +$Key = New-Object Byte[] 16   # You can use 16, 24, or 32 for AES
 +[Security.Cryptography.RNGCryptoServiceProvider]::​Create().GetBytes($Key)
 +$Key | out-file "​.\key"​
 +</​code>​
 +Now, use the key to save encrypted password to disk
 +<code powershell Create password>​
 +param (
 +    [Parameter(Mandatory=$true)][string]$Password = $( Read-Host "Input password, please"​ )
 + )
 +$Key = Get-Content "​.\key"​
 +$Password | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString -Key $key | out-file "​.\pwd"​
 +</​code>​
 +And finally use the key to get the password from disk and create credentials with it.
 +<code powershell Convert to credential>​
 +$Key = Get-Content "​.\key"​
 +$User = "​CONTOSO\someuser"​
 +$Pass = Get-Content "​.\pwd"​
 +$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, ($Pass | ConvertTo-SecureString -Key $key)
 +</​code>​
  
 +Key is used so any user can decrypt the password. If no key is used, the string value produced is bount to the current users GUID
windows/scripting/ps_ss.txt · Last modified: 2017/08/10 13:00 (external edit)