Wednesday, August 25, 2010

PowerShell: Storing and retrieving secrets

function StoreSecret($plain, $subkeyPath, $secretRegValue)
{
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Security")
$secret = [System.Security.Cryptography.ProtectedData]::Protect([System.Text.Encoding]::UTF7.GetBytes($plain), $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)
$subkey=[Microsoft.Win32.Registry]::LocalMachine.CreateSubKey($subkeyPath)
[void]$subkey.SetValue($secretRegValue, $secret, [Microsoft.Win32.RegistryValueKind]::Binary)
}

function RetrieveSecret($subkeyPath, $secretRegValue)
{
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Security")
$secret = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($subkeyPath).GetValue($secretRegValue)
$plain = [System.Text.Encoding]::UTF7.GetString([System.Security.Cryptography.ProtectedData]::Unprotect($secret, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser))
return $plain
}

# set needed constants
$subkeyPath = "Software\Pepino";
$secretRegValue = "Secret";

function StoreMySecret($plain)
{
StoreSecret -plain $plain -subkeyPath $subkeyPath -secretRegValue $secretRegValue
}

function RetrieveMySecret()
{
$plain = RetrieveSecret -subkeyPath $subkeyPath -secretRegValue $secretRegValue
return $plain
}

# store secret
$plain="boquita"
Write-Host "Secret is `"$plain`"" -BackgroundColor Black -ForegroundColor Yellow
StoreMySecret -plain $plain

# retrieve secret
$plain = RetrieveMySecret
Write-Host "Recovered secret is `"$plain`"" -BackgroundColor Black -ForegroundColor Yellow

No comments: