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
Start Visual Studio .NET and create a new C# ASP.NET Web application called DPAPIClientWeb.
Add a reference to the DataProtector.dll assembly, previously created in “How To: Create a DPAPI Library.”
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;
Add the controls listed in Table 1 to WebForm1.aspx.
|
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.
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 = "";
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 = "";
On the Build menu, click Build Solution.