[powershell]Encrypt password file

A real life example for encrypting password as an encrypted file and reuse whenever you need it.
this example is demonstrated for packaging http header for calling rest api.

#If you use this script the first time you need to create an encrypted password file.
function Obfuscate_Password($username){
    if ((Test-Path .\fwr_s.do) -eq $true) {
    $password = Get-Content ".\fwr_s.do" | ConvertTo-SecureString
    $credential = New-Object System.Management.Automation.PSCredential($username,$password)
    } else {
        Read-Host $username -AsSecureString | ConvertFrom-SecureString | Out-File -NoClobber .\fwr_s.do
        #This is to allow time for the file to be written, otherwise there is a possibility that invoke-restmethod will throw an exception that is really weird.
        #Eg. Invoke-RestMethod : You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
        Start-Sleep -Seconds 2
        $password = Get-Content ".\fwr_s.do" | ConvertTo-SecureString
        $credential = New-Object System.Management.Automation.PSCredential($username,$password)
        }
    return $credential.GetNetworkCredential().Password
}

#To prepare the header for API call.
$usr = "admin"
$pwd = Obfuscate_Password($usr)
$cred = "${usr}:${pwd}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($cred)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$headers = @{ Authorization = $basicAuthValue }
Advertisements
This entry was posted in Powershell, Scripting and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s