Data Protection API (DPAPI)

I've noticed that some recent blog entries talk about the new .NET framework supporting Data Protection API.

What is the Data Protection API? The DPAPI is used to hide secrets like connection strings and user credentials that are typically stored in a config file. Instead of storing the plain text, you can use DPAPI to encrypt and decrypt the secrets at a machine or user specific level.

A couple years ago I posted a sample DPAPI component on GotDotNet. It's still there and you can use it until the real Data Protection API comes out with the next Visual Studio. There are some warts with this one so read the comments people posted in the download link.

The component comes with a WinForms and WebForms example:

 

Code behind the Encrypt button:

 
1private void Encrypt_Click(object sender, System.EventArgs e)

2  {

3   byte[] entropy = new byte[0];

4   if (UseEntropy.Checked)

5   {

6    entropy = Encoding.Unicode.GetBytes(EntropyText.Text);

7   }

8

9   DataProtector dp = new DataProtector(Store.MachineStore);

10   byte[] dataToEncrypt = Encoding.Unicode.GetBytes(SecretText.Text);

11   

12   try

13   {

14    CipherText.Text = Convert.ToBase64String(dp.Encrypt(dataToEncrypt, entropy));

15   }

16   catch (Exception ex)

17   {

18    MessageBox.Show(ex.Message);

19   }

20  

21  }

 

Code behind the Decrypt button:

 
1private void Decrypt_Click(object sender, System.EventArgs e)

2  {

3   byte[] entropy = new byte[0];

4   if (UseEntropy.Checked)

5   {

6    entropy = Encoding.Unicode.GetBytes(EntropyText.Text);

7   }

8

9   DataProtector dp = new DataProtector(Store.MachineStore);

10   byte[] dataToDecrypt = Convert.FromBase64String(CipherText.Text);

11   

12   try

13   {

14    DecryptResults.Text = Encoding.Unicode.GetString(dp.Decrypt(dataToDecrypt, entropy));

15   }

16   catch (Exception ex)

17   {

18    MessageBox.Show(ex.Message);

19   }

20  

21  }

 

The DataProtector class imports CryptProtectData and CryptUnprotectData from the CryptoAPI to do the work.

Other options:

  1. The .Net Security Blog has two articles on DPAPI.
  2. MSDN has an article on DPAPI that you could use to construct a component.
  3. Jerry Dixon has an excellent DPAPI wrapper posted on his blog.