How to store secrets on a machine... Using the new ProtectData class in the .Net Framework 2.0

If you haven't read How to store secrets on a machine from Keith Brown's book-in-a-wiki, you should it is a great read. It talks about how to use the DPAPI to store data locally on a machine. Here is an excerpt from it about the ProtectedData class provided in .Net 2.0:

The DataProtection class

Version 2.0 of the .NET Framework introduces a class called DataProtection that wraps DPAPI. It's simple to use; in fact, it looks almost exactly like the wrapper class I provided above. I've shown an example in figure 70.2.

using System; 
using System.Text;
using System.Security.Cryptography;
class Program
{
   const string applicationEntropy = "Some application secret";
   static void Main()
   {
      string secret = "Attack at dawn";
      Console.WriteLine("Encrypting: {0}", secret);
      string base64Ciphertext = Encrypt(secret);
      Console.WriteLine("Decrypting: {0}", base64Ciphertext);
      Console.WriteLine("Result: {0}", Decrypt(base64Ciphertext));
   }
   static string Encrypt(string plaintext)
   {
      byte[] encodedPlaintext = Encoding.UTF8.GetBytes(plaintext);
      byte[] encodedEntropy = Encoding.UTF8.GetBytes(applicationEntropy);

      byte[] ciphertext = ProtectedData.Protect(encodedPlaintext,
         encodedEntropy, DataProtectionScope.LocalMachine);
      return Convert.ToBase64String(ciphertext);
   }
   static string Decrypt(string base64Ciphertext)
   {
      byte[] ciphertext = Convert.FromBase64String(base64Ciphertext);
      byte[] encodedEntropy = Encoding.UTF8.GetBytes(applicationEntropy);


      
      byte[] encodedPlaintext = ProtectedData.Unprotect(ciphertext,
         encodedEntropy, DataProtectionScope.LocalMachine);
      return Encoding.UTF8.GetString(encodedPlaintext);
   }
}
Figure 70.2: Wrapping DPAPI in Managed C#

No Comments