Created
July 7, 2014 14:45
-
-
Save AdilHindistan/052e317421505eb458d6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ##AH - AdilHindistan | |
| # PowerShell Encrypting password for re-use | |
| # From http://stackoverflow.com/questions/13842611/how-to-pass-credentials-to-rename-command | |
| If you're always running this on the same machine or the associated account roams then IIRC you can rely on DPAPI to store the key like so: | |
| # Capture once and store to file | |
| $passwd = Read-Host "Enter password" -AsSecureString | |
| $encpwd = ConvertFrom-SecureString $passwd | |
| $encpwd | |
| $encpwd > $path\password.bin | |
| # Later pull this in and restore to a secure string | |
| $encpwd = Get-Content $path\password.bin | |
| $passwd = ConvertTo-SecureString $encpwd | |
| # Extract a plain text password from secure string | |
| $bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwd) | |
| $str = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) | |
| [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) | |
| $str | |
| If that doesn't work, you can use this approach but it not as secure as the above approach: | |
| $key = 1..32 | ForEach-Object { Get-Random -Maximum 256 } | |
| $passwd = Read-Host "Enter password" -AsSecureString | |
| $encpwd = ConvertFrom-SecureString $passwd -Key $key | |
| $encpwd | |
| # Could easily modify this to store username also | |
| $record = new-object psobject -Property @{Key = $key; EncryptedPassword = $encpwd} | |
| $record | |
| $record | Export-Clixml $path\portablePassword.bin | |
| # Later pull this in and restore to a secure string | |
| $record = Import-Clixml $path\portablePassword.bin | |
| $passwd = ConvertTo-SecureString $record.EncryptedPassword -Key $record.Key | |
| # Extract a plain text password from secure string | |
| $bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwd) | |
| $str = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) | |
| [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) | |
| $str |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment