Sunday, February 17, 2013

Securely storing passwords with Powershell

I just stumbled upon the Data Protection API from Microsoft that easily solves the problem of storing passwords and other sensitive data in scripts. It is really simple to use it from Powershell as can be seen below.

How to protect data?

The snippet provided here accepts a string and a file name as input and will store the encrypted string into the  specified file.
Add-Type -assembly System.Security
function New-Password($password, $file)
    $plainText = [System.Text.Encoding]::Unicode.GetBytes($password)
    $cipherText = [System.Security.Cryptography.ProtectedData]::Protect( $plainText, $null, 'CurrentUser')
    $cipherText | Set-Content -Encoding byte -Path $file

How to unprotect data?

The function defined here takes the data from the file, decrypt it and transforms it back into a string. Simple enough!
Add-Type -assembly System.Security
function Get-Password($file)
    $cipherText = Get-Content -Encoding byte -Path $file
    $plainText = [System.Security.Cryptography.ProtectedData]::Unprotect($cipherText, $null, 'CurrentUser')   
    $password = [System.Text.Encoding]::Unicode.GetString($plainText)

You have no excuse anymore to store your password in clear text inside your scripts!