X

Powershell using DPAPI to store secure data in Registry

Powershell-dpapi

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.

DPAPI only works in windows, if you are on linux environment there is no DPAPI

What is DPAPI?

From Wikipedia we get this definition

DPAPI (Data Protection Application Programming Interface) is a simple cryptographic application programming interface available as a built-in component in Windows 2000 and later versions of Microsoft Windows operating systems. In theory the Data Protection API can enable symmetric encryption of any kind of data; in practice, its primary use in the Windows operating system is to perform symmetric encryption of asymmetric private keys, using a user or system secret as a significant contribution of entropy.

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

powershell-execute-command

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#.

Categories: .NET powershell
Taswar Bhatti:
Related Post