I wanted to store some data into registry but how do I store it such that it is secure for my application to read later on. Well there is a way using Powershell to store data into Registry using DPAPI which uses the machine key to store the information. As you know the only way to store data securely is by using encryption and DPAPI provides us with that.
What is DPAPI?
From Wikipedia we get this definition
Now that we know it uses the machine key we can write some code to store some value into our registry using powershell. We will be writing into the Wow64 registry since we will most likely use a 64bit application later on. If you need to write to 32bit also just remove the wow64node.
Powershell using DPAPI to store secure data in Registry
What we will do is use SecureString to read the data and convert the secure string into a hash, then we will base64 encode it and store it to the registry, one could just leave it as it and not base64 it. We use the New-ItemProperty to create the value into the registry.
$registryKey = "SecureDataKey"
$path= "HKLM:\SOFTWARE\Wow6432Node\MySoftware\Data\"
If (!(Test-Path $path))
{
[System.Exception]
Write-Host -Foreground Red "Unable to read registry path. $path"
}
$sec = Read-Host "Enter SecureKey for " -AsSecureString
$hash = $sec | ConvertFrom-SecureString
$Bytes = [System.Text.Encoding]::Unicode.GetBytes($hash)
$basehash =[Convert]::ToBase64String($Bytes)
New-ItemProperty -Path $path -Name $registryKey -Value $basehash -PropertyType "String"
Write-Host "Saved in registry OK" -Fore Green
So here it is how to store data into your registry using DPAPI. In my next post I will show how to read back the value using C#.