This would be the second part of the blog post where we used powershell to store some secure data into our registry and have used DPAPI to encrypt the data. I wanted to cover how I would read the data back from the registry in my C# application. An example of C# using DPAPI to read data from Registry.
Feel free to read the blog post on Powershell using DPAPI to store secure data in Registry
C# using DPAPI to read data from Registry
I will be using a Console application with .NET Framework 4.6 just to show how I would read the registry and use System.Security.Cryptography to decrypt the data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class Program { static void Main(string[] args) { var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\MySoftware\Data\"); if (key != null) { var cipher = (string) key.GetValue("SecureDataKey"); var hashedBytes = Convert.FromBase64String(cipher); var exportedData = Encoding.Unicode.GetString(hashedBytes); var length = exportedData.Length / 2; var encryptedData = new byte[length]; for (int index = 0; index < length; ++index) { var data = exportedData.Substring(2 * index, 2); encryptedData[index] = byte.Parse(data, NumberStyles.HexNumber, CultureInfo.InvariantCulture); } var data = ProtectedData.Unprotect(encryptedData, (byte[])null, DataProtectionScope.LocalMachine); Console.WriteLine(Encoding.Unicode.GetString(data)); //output whatever was stored in registry Console.ReadKey(); } } |
If we run this application we will see the data that we have stored in the registry.
Leave A Comment