Team LiB
Previous Section Next Section

1. Create an ASP.NET Client Web Application

This procedure creates an ASP.NET client Web application that will call the DPAPI class library to encrypt and decrypt data stored within the Web.config file.

To create an ASP.NET client Web application

  1. Start Visual Studio .NET and create a new C# ASP.NET Web application called DPAPIClientWeb.

  2. Add a reference to the DataProtector.dll assembly, previously created in “How To: Create a DPAPI Library.”

  3. Open WebForm1.aspx.cs and add the following using statements to the top of the file beneath the existing using statements.

    using System.Text;
    using DataProtection;
    
  4. Add the controls listed in Table 1 to WebForm1.aspx.

    Table 1: WebForm1.aspx controls

    Control Type

    Text

    ID

    Button

    Encrypt

    btnEncrypt

    Button

    Decrypt

    btnDecrypt

    TextBox

     

    txtDataToEncrypt

    TextBox

     

    txtEncryptedData

    TextBox

     

    txtDecryptedData

    Label

     

    lblError

    Label

    Data To Encrypt

     

    Label

    Encrypted Data

     

    Label

    Decrypted Data

     

    Your Web form should look similar to Figure 1.

    Click To expand
    Figure 1: DPAPIClientWeb Web Form

  5. Double-click the Encrypt button to create a button click event handler.

    DataProtector dp = new DataProtector( DataProtector.Store.USE_MACHINE_STORE );
    try
    {
     byte[] dataToEncrypt = Encoding.ASCII.GetBytes(txtDataToEncrypt.Text);
     // Not passing optional entropy in this example
     // Could pass random value (stored by the application) for added security
     // when using DPAPI with the machine store.
     txtEncryptedData.Text =
            Convert.ToBase64String(dp.Encrypt(dataToEncrypt,null));
    }
    catch(Exception ex)
    {
     lblError.ForeColor = Color.Red;
     lblError.Text = "Exception.<br>" + ex.Message;
     return;
    }
    lblError.Text = "";
    
  6. Return to the Web form and double-click the Decrypt button. Add the following code to the button click event handler.

    DataProtector dp = new DataProtector(DataProtector.Store.USE_MACHINE_STORE);
    try
    {
      byte[] dataToDecrypt = Convert.FromBase64String(txtEncryptedData.Text);
      // Optional entropy parameter is null. 
      // If entropy was used within the Encrypt method, the same entropy parameter
      // must be supplied here
      txtDecryptedData.Text = 
                Encoding.ASCII.GetString(dp.Decrypt(dataToDecrypt,null));
    }
    catch(Exception ex)
    {
      lblError.ForeColor = Color.Red;
      lblError.Text = "Exception.<br>" + ex.Message;
      return;
    }
    lblError.Text = "";
    
  7. On the Build menu, click Build Solution.


Team LiB
Previous Section Next Section